8

I have a frame of 22 bytes. The frame is the input stream from an accelerometer via bluetooth. The acceleromter readings are a 16 bit number split over two bytes.

When i try to merge the bytes with buffer[1] + buffer[2], rather than adding the bytes, it just puts the results side by side. so 1+2 = 12.

Could someone tell me how to combine these two bytes to obtain the original number. (btw the bytes are sent little endian)

Thanks

2

2 Answers 2

27

here's the code:

public static short twoBytesToShort(byte b1, byte b2) {
          return (short) ((b1 << 8) | (b2 & 0xFF));
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thats great, Thanks a million
@Shane, if this works for you, you should 'Accept' the answer :)
Why are you OR'ing the bottom byte by 0xFF?
The &OxFF is a must!!! This is due to the fact that some Java architectures do integer promotions so if 'b2' > 127 the result will have a negative sign (highest bit of 'b2' became the sign bit since it was promoted to 32'th bit of integer). I have personally seen this happening On Android 6 devices
-1

Here's a better answer that might make a little more sense...

public static short twoBytesToShort(byte b1, byte b2) {
          return (short) ((b1 << 8) | b2);
}

(b2 & 0xFF) comes out with the same exact binary pattern.

1 Comment

That is completely wrong and might yield wrong result. The &OxFF is a must!!! This is due to the fact that some Java architectures do integer promotions so if 'b2' > 127 the result will have a negative sign (highest bit of 'b2' became the sign bit since it was promoted to 32'th bit of integer). I have personally seen this happening (On Android 6 devices)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.