Signed Short Decoder

Hello,
I am struggling with the decoder.

I want to return an signed short 16bit.
This is how my payload looks like in hex: 8A 00 FF C3 00 BF 00 00 00 00 00 FE

retValue.x1 = ((bytes[2] << 8) + bytes[3]);

retValue.x1 should be -61. (11111111 11000011)
What I get is 65475.

How can I get a signed short?

Regards
Martin

I found a solution… Quite easy just taking this value - 65536;

Regards

But: you should not always subtract that, as that would not work for positive values. Only subtract when the value exceeds the maximum of a signed short, that is: 32767 or 0x7FFF. Of if the leftmost bit of the MSB is 1, so if (bytes[2] & 0x80).

As JavaScript bitwise operations always assume 32 bits signed integers, the magic word is sign extension:

// Sign-extend to 32 bits to support negative values, by shifting
// 24 bits to the left (16 too far), followed by a sign-propagating
// right shift of 16 bits, to effectively shift 8 bits:
retValue.x1 = bytes[2]<<24>>16 | bytes[3];

(Also note that I used the bitwise OR rather than arithmetic addition, which saves you from the parentheses.)

1 Like