Hex To Decimal and Decimal to Hex

Previous topic - Next topic

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) Select

// --------------------------------- //
// 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

Kitty Hello


MrTAToad


ketil

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

Because that would exclude all GLBasic users that doesn't have the full package.

ketil

Ahhh ... didn't think about that.
"Sugar makes the world go 'round. Caffeine makes it spin faster."

Qedo

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
ad maiora

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

Kitty Hello

There is a builtins HEX$(), are you aware of that?

Qedo

HEX$() ? I thought it only transforms from decimal to hexadecimal.
Or am I wrong?
I need the opposite. HEX2DEC

Kitty Hello

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)

Qedo

Thanks Gernot for the great help  :booze:, However for high hex, like 0xFFFFFFFF the strtol function overflows. It seems to be better strtoul.
ad maiora

a#=hex2dec("F234FFF0")
PRINT a,0,0
SHOWSCREEN
MOUSEWAIT
END

IMPORT "C" unsigned long strtoul(const char* str, int endptr, int base)
FUNCTION hex2dec#: str$
   LOCAL n# = strtoul(str$, 0, 16)
   RETURN n
ENDFUNCTION