Search code examples
javabyte-shifting

Does left shifting a byte change the signed bit in Java?


I have

byte i = 30;
i <<= 3;
System.out.println(i);

Which I believe would change 00011110 to 11110000 Does doing this actually put a one into the signed bit, or is the one that would be in the signed bit cut off and the signed bit is changed some other way?

Also, this prints out -16. Why is this? I thought 11110000 in base 10 was equal to -112, I'm confused where the -16 comes from.


Solution

  • From right to left, the bits of a byte represent 1, 2, 4, 8, 16, 32, 64 and -128.

    We call it the sign bit, but really it represents -128.

    11110000 is therefore 16 + 32 + 64 - 128 == -16.