How to reconstruct a signed 32 bit value (int) from array of 4 bytes?

brainfart

Member
Licensed User
Longtime User
Hello everyone.
This should be simple yet I am struggling.
I have an array of 4 bytes that were sent from hardware (serial Bluetooth) that represent a signed 32 bit value.
I am trying to reassemble it to form an signed Integer (in Android that means 32bit).
First byte (index 0) in array is most significant.
I tried creating a temporary Integer then copying the byte to it, shifting left 24 bits and Bit.Or-ing it with another temp then same for next byte shifted by 16 and 3rd shifted by 8 then Bit.Or-ing it with last byte but the answer is wrong.
Number jump by 127 etc every time I hit some bytes 0-crossing from 0x00 to 0xff etc.
I then tried just adding the shifted value instead of Bit.Or-ing it but I also can't get the correct result.
Needless to say, I am having trouble handling the signed numbers.
Can someone help unstuck my brain from this loop :BangHead:.

Thanks,

Mike S

B4X:
    Dim raw As Int
    Dim XYZ_arr(4) As Byte 
    '.   
    '.... assume the array now holds the 4 bytes from 32 bit signed value
    '.
    Dim Temp As Int
    Temp = XYZ_arr(0)
    Temp = Bit.ShiftLeft(Temp,24)
    raw = Temp
    Temp = XYZ_arr(1)
    Temp = Bit.ShiftLeft(Temp,16)
    raw = raw + Temp
    Temp = XYZ_arr(2)
    Temp = Bit.ShiftLeft(Temp,8)
    raw = raw + Temp
    Temp = XYZ_arr(3)
    raw = raw + Temp
    lblDebug.Text = raw
 

brainfart

Member
Licensed User
Longtime User
Thanks MLDev.
Coming from assembly language and unsigned math i figured the left shift 8 bits and * 256 are equivalent but i guess I am wrong.

Your method works great.

Many thanks.:sign0188:
 
Upvote 0

MLDev

Active Member
Licensed User
Longtime User
Thanks MLDev.
Coming from assembly language and unsigned math i figured the left shift 8 bits and * 256 are equivalent but i guess I am wrong.

Your method works great.

Many thanks.:sign0188:

It is equivalent. raw * 256 is just faster to type than Bit.ShiftLeft(raw, 8). ;)

Bit.And(XYZ_arr(j), 255) converts the signed byte XYZ_arr(j) to an unsigned byte and returns it as an integer.
 
Last edited:
Upvote 0
Top