Search code examples
javabyte-shifting

Java bit unsigned shifting (>>>) give strange result


I have this code:

int i = 255;
byte b = (byte) i;
int c;
System.out.println(Integer.toBinaryString( i));
System.out.println("b = " + b); // b = -1
c=b>>>1;
System.out.println(Integer.toBinaryString( c));
System.out.println(c);

But I can't understand how it works. I think that unsigned shifting to 255(11111111) should give me 127(0111111) but it doesn't. Is my assumption wrong?


Solution

  • Shift operators including >>> operate on ints. The value of b, which is -1 because byte is signed, is promoted to int before the shift. That is why you see the results that you see.

    The reason why 255 is re-interpreted as -1 is that 255 has all its eight bits set to one. When you assign that to a signed 8-bit type of byte, it is interpreted as -1 following two's complement rules.