Search code examples
javabyteshort

Why is converting two bytes just with shifting is incocrrent?


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.


Solution

  • 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))