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

Shane
  • 249
  • 1
  • 3
  • 10
  • Look into bitwise and bit-shift operations. http://leepoint.net/notes-java/data/expressions/bitops.html – HXCaine May 24 '10 at 10:09
  • Have a look at this question: http://stackoverflow.com/questions/1026761/how-to-convert-a-byte-array-to-its-numeric-value-java – David Webb May 24 '10 at 10:20

2 Answers2

27

here's the code:

public static short twoBytesToShort(byte b1, byte b2) {
          return (short) ((b1 << 8) | (b2 & 0xFF));
}
reflog
  • 7,587
  • 1
  • 42
  • 47
  • Thats great, Thanks a million – Shane May 24 '10 at 12:42
  • @Shane, if this works for you, you should 'Accept' the answer :) – reflog May 25 '10 at 07:49
  • 1
    Why are you OR'ing the bottom byte by 0xFF? – EntangledLoops Apr 28 '15 at 20:34
  • 1
    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 – DanielHsH Oct 09 '15 at 16:48
-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.

RedXVIIII
  • 7
  • 1
  • 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) – DanielHsH Oct 09 '15 at 16:47