1

I read this topic about shifting. I thought that if I have two bytes:

byte hi = //...
byte low = //...

why can't I just do that

short s = (short)((hi << 8) | low)

Why is it incorrect? I thought we 8 bits left shift most significant and leave least significant byte as is. And then just bitwise or them.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • you should use ByteBuffer for that like: ByteBuffer.wrap(valBytes).order(ByteOrder.LITTLE_ENDIAN).getShort(); – Fady Saad Aug 13 '17 at 03:34
  • @FadySaad I'm aware of `ByteBuffer`. I'm interested in understanding bit-shift operations... just that :) – St.Antario Aug 13 '17 at 03:35

1 Answers1

2

This gives a wrong result because bytes are signed and extended to int to do the calculations. So take for example

hi = (byte)0x01;
low = (byte)0x80;

then you calculate:

0x00000100 | 0xffffff80 -> 0xffffff80

which is not the desired result.

You could write it like this instead:

short s = (short)((hi << 8) | (low & 0xff))
Henry
  • 42,982
  • 7
  • 68
  • 84