Codesnippets > Math
Hex To Decimal and Decimal to Hex
MrTAToad:
No checking is done with the conversion from hex to decimal to make sure the passed string is a valid hex character.
--- Code: (glbasic) ---// --------------------------------- //
// Project: HexADecimal
// 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
--- End code ---
Kitty Hello:
Very nice!
MrTAToad:
Thanks!
ketil:
It's cool, but why not just go inline C and sprintf or something ?
Moru:
Because that would exclude all GLBasic users that doesn't have the full package.
Navigation
[0] Message Index
[#] Next page
Go to full version