B4J Question Getting 32 bit int from 4 bytes using B4J


Active Member
Licensed User
I am currently getting four bytes that contains (from Arduino code):
  int32_t LatGPS = 395192359;
  byte bufflen = 4;
  byte XBUFFER[bufflen]="";
  XBUFFER[0] = LatGPS & 0xFF;
  XBUFFER[1] = (LatGPS >> 8) & 0xFF;
  XBUFFER[2] = (LatGPS >> 16) & 0xFF;
  XBUFFER[3] = (LatGPS >> 24) & 0xFF;

In Arduino code I can get the reconstructed number by:
  int32_t reconstructedValue;
  reconstructedValue = ((int32_t)XBUFFER[3] << 24) | ((int32_t)XBUFFER[2] << 16) | ((int32_t)XBUFFER[1] << 8)  | (int32_t)XBUFFER[0];

How do I get the reconstructedValue using B4J?
You can do it with Bit methods or ByteConverter or RandomAccessFile:
Dim bc As ByteConverter
Dim b() As Byte = bc.IntsToBytes(Array As Int(395192359))


Licensed User
How do I get the reconstructedValue using B4J?

If you actually want to go from 4 bytes to 32-bit reconstructedValue, instead of the other way around, maybe a Sub like:
Sub FourBytesToInt(B3 As Byte, B2 As Byte, B1 As Byte, B0 As Byte) As Int
    Dim I As Int =                  Bit.And(B3, 0xFF)
    I = Bit.Or(Bit.ShiftLeft(I, 8), Bit.And(B2, 0xFF))
    I = Bit.Or(Bit.ShiftLeft(I, 8), Bit.And(B1, 0xFF))
    I = Bit.Or(Bit.ShiftLeft(I, 8), Bit.And(B0, 0xFF))
    Return I
End Sub
and used like:
reconstructedValue = FourBytesToInt(XBUFFER[3], XBUFFER[2], XBUFFER[1], XBUFFER[0])

which has the advantage of you can pick and choose the four bytes individually ie they don't need to be four contiguous bytes in an array on a four-byte boundary, and there's no ambiguity about whether the current endiness mode is big or little or even mixed.

There is still the possible problem that it's returning a SIGNED integer, which might or might not be what you're expecting, and so you might need to use Bit.AndLong(reconstructedValue, 0xFFFFFFFF) to unsign it.
Upvote 0