Android Question Convert Hex to Dec Problem

tzfpg

Active Member
Licensed User
HI,

I try to convert hex code to decimal but it have problem :

java.lang.NumberFormatException: For input string: "FB461E4D"

my code is

B4X:
Dim str As String = "FB461E4D"
Dim lng As Long = Bit.ParseInt(str,16)
Log(lng)

Any solution for this, Thanks
 

Midimaster

Active Member
Licensed User
This would work imediately, but the base is not a string...

B4X:
Dim lng As Long = 0xFB461E4D
Log(lng)


Do you need it from a string? Don't know whether there is a special B4A command... but this works:

B4X:
    Dim Str As String="FB461E4D"
    Dim lng As Long= StringToLong(Str)
    Log(lng)

Sub StringToLong(Str As String) As Long
    Str= "0000000000000000" & Str
    Str=Str.SubString(Str.Length-16)
    Dim converter As ByteConverter
    Dim a() As Byte=converter.HexToBytes(Str)
    Dim lng() As Long =converter.LongsFromBytes(a)
    Return lng(0)
End Sub
 
Last edited:
Upvote 0

Erel

Administrator
Staff member
Licensed User
The reason that the above code fails is that it treats the hex code as a positive number and it is larger than the maximum value an int can hold.

B4X:
Sub AppStart (Args() As String)
    Dim i As Int = 0xFB461E4D
    Log(i)
    Log(StringToInt("FB461E4D"))
    'unsigned value:
    Log(StringToUnsignedInt("FB461E4D"))
End Sub

Sub StringToInt(Str As String) As Int
    Dim converter As ByteConverter
    Dim ii() As Int = converter.IntsFromBytes(converter.HexToBytes(Str))
    Return ii(0)
End Sub

Sub StringToUnsignedInt (Str As String) As Long
    Dim converter As ByteConverter
    Dim a(8) As Byte
    Dim i() As Byte = converter.HexToBytes(Str)
    Bit.ArrayCopy(i, 0, a, 4, 4)
    Dim ll() As Long = converter.LongsFromBytes(a)
    Return ll(0)
End Sub
 
Upvote 0

Midimaster

Active Member
Licensed User
The reason that the above code fails is that it treats the hex code as a positive number and it is larger than the maximum value an int can hold.

thank for pointing to the perfect solution.

... I updated my not working sub in the post aove.

But now I have one question-... If somebody writes "FB461E4D" and wants to convert it to long. Is this "FB461E4D" a signed INTEGER or a unsigned LONG by definition? Do I have to write "00000000FB461E4D" to explizit say "this is long"?
 
Upvote 0
Top