B4J Question Hex to int with ByteConverter

Drago Bratko

Active Member
Licensed User
Longtime User
I have simple function for converting hex string to integer.

B4X:
Sub TestHexToInt(Str As String)
    Dim converter As ByteConverter
    Dim b() As Byte, i() As Int
    b = converter.HexToBytes(Str)
    i = converter.IntsFromBytes(b)
    
    Log(b(0))
    Log(i(0))
End Sub

For test calls, for example I call this:
B4X:
    TestHexToInt("01")
    TestHexToInt("55")
    TestHexToInt("E0")

Question is why "i" array in function "TestHexToInt" is always empty?
 
Check the length of b(). You only seem to be specifying two bytes but ByteConverter needs four bytes to create an Int as it divides the length of the byte array by 4 to know the length of the Int array to create for the conversion so you are getting a zero length i() array.

As an aside I wrote I ByteConverter in the very early days of B4A (2011 according to the timestamp on my copy of the source code) and Erel adopted it as one of the official libraries together with several other of my early libraries.
 
Upvote 0
Just add
Code:
Sub TestHexToInt(Str As String)
    If Str.Length < 8 Then
        Str = "00000000" & Str
        Str = Str.SubString(Str.Length - 8)
    End If
...
 
Upvote 0
Thanks to all.
Just to give response to others who may need it, both ways (Daestrum and emexes solution) works in my case.
 
Upvote 0

Similar Threads

  • Article Article
Android Code Snippet [B4X] Hex string to number
Replies
0
Views
6K
  • Locked
  • Article Article
Replies
6
Views
10K
Back
Top