B4J Question [B4X] Hex string to number - IntsFromBytes need formatted input

rtek1000

Active Member
Licensed User
Longtime User
I got errors when trying to convert an "ABC" value to Int, using this sample code:

B4X:
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

Source: https://www.b4x.com/android/forum/threads/b4x-hex-string-to-number.122739/#content

I found this reference:

the IntsFromBytes (which expects 4 bytes per int).
Source: https://www.b4x.com/android/forum/t...r-not-returning-array-of-ints.115710/#content

I actually believe that the IntsFromBytes function should complement the missing bytes so that the value could be obtained.

But as this does not happen, there is an adaptation so that the input variable has the correct formatting:

B4X:
Sub StringToInt(Str As String) As Int
    If Str.Length = 0 Or Str.Length > 8 Then
        Return 0
    End If
    
    If Str.Length <> 8 Then
        For i = Str.Length To 7
            Str = "0" & Str
        Next
    End If
    
    Dim converter As ByteConverter
    Dim ii() As Int = converter.IntsFromBytes(converter.HexToBytes(Str))
    Return ii(0)
End Sub
 

agraham

Expert
Licensed User
Longtime User
I actually believe that the IntsFromBytes function should complement the missing bytes so that the value could be obtained.
As the writer of this library I totally disagree. IntsFromBytes is part of a set of methods to convert between primitive types. As such it expects a Byte array that corresponds to the individual bytes values of an array of Ints. It is up to you to meet its expectations as it is an error not not have sufficient bytes for complete individual Int values
 
Upvote 0

rtek1000

Active Member
Licensed User
Longtime User
As the writer of this library I totally disagree. IntsFromBytes is part of a set of methods to convert between primitive types. As such it expects a Byte array that corresponds to the individual bytes values of an array of Ints. It is up to you to meet its expectations as it is an error not not have sufficient bytes for complete individual Int values

The common user, just wants to use the function, every time an error of this type occurs, it can be one less user using the B4X compiler.

Not all users can easily debug code, especially if they're just starting out.

I came here to try to help other people, not make fun of them because they don't know how to format an input variable.

That's why I suggested a code to work around the lack of intelligence in the function.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
I came here to try to help other people, not make fun of them because they don't know how to format an input variable.
What on earth do you mean by this comment. I made fun of no-one - I just stated the intent of the implementation of the method.
 
Upvote 0
Top