Android Question IntsFromBytes byte converter from two bytes fails

jimseng

Active Member
Licensed User
Longtime User
Hello. I am trying to get an integer from two bytes but I think IntsFromBytes expects 4 bytes so the length is zero and I am not getting a result. So for example if I have 2 bytes: 0x00 and 0x78 I would expect an integer of 120 but I get nothing.
Dim dbA() As Byte = bb.SubArray2(9,11) 'duration a
Dim intda() As Int = bc.IntsFromBytes(dbA)
B4X:
Dim dbA() As Byte = bb.SubArray2(9,11) 'duration a
    Dim intda() As Int = bc.IntsFromBytes(dbA)

Just wondering what I should do here instead?
Thanks
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Another option without ByteConverter

B4X:
' Convert 2 bytes (little endian) to a signed int.
' b(0) = LSB, b(1) = MSB.
' Example <code>
' Log(BytesToInt(Array As Byte(0x78, 0x00)))
' Result = 120
' Log(BytesToInt(Array As Byte(0x88, 0xFF)))
' Result = -120
' </code>
Public Sub BytesToInt(b() As Byte) As Int
    If b.Length < 2 Then Return 0
    Dim value As Int = Bit.Or(Bit.And(b(0), 0xFF), Bit.ShiftLeft(Bit.And(b(1), 0xFF), 8))
    If value > 32767 Then value = value - 65536   ' sign extend
    Return value
End Sub
 
Last edited:
Upvote 0
Top