### Author Topic: Hex To Decimal and Decimal to Hex  (Read 4778 times)

• Guest
##### Hex To Decimal and Decimal to Hex
« on: 2009-Mar-04 »
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

#### Kitty Hello

• code monkey
• Prof. Inline
• Posts: 10656
• here on my island the sea says 'hello'
##### Re: Hex To Decimal and Decimal to Hex
« Reply #1 on: 2009-Mar-04 »
Very nice!

• Guest
##### Re: Hex To Decimal and Decimal to Hex
« Reply #2 on: 2009-Mar-04 »
Thanks!

#### ketil

• Mr. Polyvector
• Posts: 117
##### Re: Hex To Decimal and Decimal to Hex
« Reply #3 on: 2010-Jul-27 »
It's cool, but why not just go inline C and sprintf or something ?
"Sugar makes the world go 'round. Caffeine makes it spin faster."

#### Moru

• Prof. Inline
• Posts: 1750
##### Re: Hex To Decimal and Decimal to Hex
« Reply #4 on: 2010-Jul-27 »
Because that would exclude all GLBasic users that doesn't have the full package.

#### ketil

• Mr. Polyvector
• Posts: 117
##### Re: Hex To Decimal and Decimal to Hex
« Reply #5 on: 2010-Jul-27 »
Ahhh ... didn't think about that.
"Sugar makes the world go 'round. Caffeine makes it spin faster."