javabinarybit-manipulationbitbit-shift

Explain how left shift works in Java


Why does the following program code output the value -32 to the console?

int num = 0xFFFFFFE;
for(int i=0; i < 4; i++) {
  num = num << 1;
  System.out.println(num);
}

The program produces the following result:

536870908
1073741816
2147483632
-32

I know that when the binary digit is shifted to the highest (31st) position, the value becomes negative.

I can't quite figure out why -32. Why not -16 or -8, namely the result is -32?

I would be glad if you could explain this to me in more detail. If you can accompany the answer with images, it will be just great.

I hope my question is not stupid.


Solution

  • This doesn't really have to do with the bit shiting as such. Java uses two's complement to represent negative numbers and the last shift makes num contain

    0xFFFFFFE0 // 11111111111111111111111111100000 in binary representation
    

    which is -32 using two's complement. You can remove the bitshifts and observe the same output:

    int num = 0xFFFFFFE0;
    System.out.println(num); // -32
    System.out.println(Integer.toBinaryString(num));