Have can I convert a HEX sting to DEC on an easy way.
I cant find any hint in the user guide :'(
Tanks
I believe Bevets wrote this
SetId "BINBASE",2
SetId "OCTBASE",8
SetId "HEXBASE",16
Declare ToBase(intValue:Int, base:Int)
Declare ToInt(strValue:String, base:Int)
Def HexStr:string
Def i:int
HexStr = "ee20e5"
OpenConsole
i = ToInt(HexStr, @HEXBASE)
Print "Hex String: " + HexStr
Print "Integer: " + Str$(i)
Print "Binary: " + ToBase(i, @BINBASE)
Print "Octal: " + ToBase(i, @OCTBASE)
Print "Hexadecimal: " + ToBase(i, @HEXBASE)
Print Input "Press Enter:",HexStr
CloseConsole
End
Sub ToBase(intValue:Int, base:Int)
' Convert an integer to a given base
' Supports bases 2 thru 36
Def result:String
Def i:Int
result = ""
If (base >= 2) & (base <= 36)
While intValue > 0
i = (intValue % base) + 1
intValue = intValue / base
result = Mid$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", i, 1) + result
EndWhile
EndIf
Return result
Sub ToInt(strValue:String, base:Int)
' Convert a string value from a given base to an integer
' Supports bases 2 thru 36
Def result, i, charValue:Int
result = 0
If (base >= 2) & (base <= 36)
For i = 1 to Len(strValue)
charValue = InStr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase$(Mid$(strValue, i, 1)))
' return -1 if character is not supported by base
If charValue > base Then Return -1
result = (result * base) + (charValue - 1)
Next i
EndIf
Return result
LarryMc
Here is one I wrote awhile back.
SUB Hex2Dec(STRING txt),UINT
INT i,pow
UINT res
res=0
FOR i=1 to LEN(txt)
pow=16^(LEN(txt)-i)
res+=(INSTR("0123456789ABCDEF",MID$(txt,i,1),1)-1)*pow
NEXT i
RETURN res
ENDSUB
Later,
Clint
thank you for your quick response clint
Torben
Just found your litte hex2dec
How cool !
How simple !
Reinhard
Torben and Reinhard,
Yes Clint's code is very beautiful, don't think I could have written it.
However, there is a problem with converting numbers, in IWB we have not been able to convert a number larger than the UINT maximum value which is 4294967295 (8 F's in hex) until recently.
If you try to convert a number greater than 4294967295 you will get the wrong answer.
Fasecero helped me along with breaking this limit, so you can now convert with a UINT64 number - the maximum is 18446744073709551615 (or 16 F's in hex).
Attached is the magic include file which breaks this limit and provides the correct answers.
How to:
1. Unzip the files.
2. Copy the UINT64.INC file to your C:\IWBDev3\Include folder.
3. Compile and run Hex2Dec64.
Enjoy,
Andy.
:)
Footnote:-
If you are wondering how you can convert the other way, that is say binary to decimal, just use the
HexToU64(a$) function - guess I should rename it.
a$ = U64ToBase(y,2) 'Convert to binary.
print
print " Number to base 2: ",a$," <- this is actually a string."
print
y = HexToU64(a$)
print
print "******* Base 2 to Base 10: ",y
print