# GLBasic forum

## Codesnippets => Math => Topic started by: MrTAToad on 2009-Mar-04

Title: Hex To Decimal and Decimal to Hex
No checking is done with the conversion from hex to decimal to make sure the passed string is a valid hex character.

Code: (glbasic) [Select]
// --------------------------------- //
// Start: Tuesday, March 03, 2009
// IDE Version: 6.174

DEBUG "Hex : "+decToHex\$(255,4)+"\n"
DEBUG "Dec : "+hexToDec("FFFF")+"\n"
END

FUNCTION decToHex\$:value%,length%=4
LOCAL digit%
LOCAL temp%
LOCAL result\$

IF length%<=0
RETURN "0"
ENDIF

result\$=""
FOR digit%=length% TO 1 STEP -1
temp%=MOD(value%,16)
IF temp%<10
result\$=CHR\$(temp%+48)+result\$
ELSE
result\$=CHR\$((temp%-10)+65)+result\$
ENDIF

value%=value%/16
NEXT

RETURN result\$
ENDFUNCTION

FUNCTION hexToDec%:hex\$
LOCAL i%
LOCAL j%
LOCAL loop%

i%=0
j%=0
FOR loop%=0 TO LEN(hex\$)-1
i%=ASC(MID\$(hex\$,loop%,1))-48
IF 9<i%
DEC i%,7
ENDIF

j%=j%*16
j%=bOR(j%,bAND(i,15))
NEXT

RETURN j
ENDFUNCTION
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Kitty Hello on 2009-Mar-04
Very nice!
Title: Re: Hex To Decimal and Decimal to Hex
Thanks!
Title: Re: Hex To Decimal and Decimal to Hex
Post by: ketil on 2010-Jul-27
It's cool, but why not just go inline C and sprintf or something ?
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Moru on 2010-Jul-27
Because that would exclude all GLBasic users that doesn't have the full package.
Title: Re: Hex To Decimal and Decimal to Hex
Post by: ketil on 2010-Jul-27
Ahhh ... didn't think about that.
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Qedo on 2021-Mar-12
the old 2009 hexToDec function fails with value xFFFFFFFF because it returns value -1 instead of 4294967295.
This instead is the one that returns the correct value. For those who had used the old one please check

FUNCTION hexToDec#:_HEX\$
LOCAL i%=0
LOCAL j#=0
LOCAL loop%
_HEX\$=UCASE\$(_HEX\$)
LOCAL start%=LEN(_HEX\$)-1
FOR loop%=start TO 0 STEP-1
i=ASC(MID\$(_HEX\$,loop,1))-48   //0=48 A=65
IF i>9
DEC i,7
ENDIF
j=j+i*POW(16,start-loop)
NEXT
RETURN j
ENDFUNCTION
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Kitty Hello on 2021-Mar-13
There is a builtins HEX\$(), are you aware of that?
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Qedo on 2021-Mar-13
HEX\$() ? I thought it only transforms from decimal to hexadecimal.
Or am I wrong?
I need the opposite. HEX2DEC
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Kitty Hello on 2021-Mar-15
Ah. Try this:
Code: (glbasic) [Select]
IMPORT "C" int strtol(const char* str, int endptr, int base)
LOCAL str\$ = "ff"
LOCAL n% = strtol(str\$, 0, 16)
Title: Re: Hex To Decimal and Decimal to Hex
Post by: Qedo on 2021-Mar-20
Thanks Gernot for the great help  :booze:, However for high hex, like 0xFFFFFFFF the strtol function overflows. It seems to be better strtoul.