0

How can I concatenate 2 byte values into a short value in java?

This:

byte b1 = 0xAC;
byte b2 = 0xAD;
short pixelShort = (short) (b1<<8 | b2);

does not work, as the result is 0xFFAD. Why is this?

Lake
  • 4,072
  • 26
  • 36
  • 1
    I did not see an _exact_ duplicate myself. b2 is negative, | operation uses ints, so (int)b2 messes up the high byte. `(short) (b1 << 8 | (b2 & 0xFF))` or such. – Joop Eggen Jul 06 '16 at 15:51
  • 1
    I was trying to answer my own question but it was marked duplicate before I could post ^^; – Lake Jul 06 '16 at 15:53
  • `ByteBuffer.wrap(new byte[] {b1, b2}).getShort()` – Joop Eggen Jul 06 '16 at 15:55

0 Answers0