Java shift operator

2019-06-27 02:12发布

问题:

Consider the following Java code:

byte a = -64; 
System.out.println(a << 1);

The output of this code is -128

I tried as follows to figure out why this is the output:

64 = 0 1000000 (the MSB is the sign bit)

-64= 1 1000000 (Tow's complement format)

Expected output after shifting: 1 0000000 (This is equal to 0, because the MSB is just a sign bit)

Please anyone explain what I am missing.

回答1:

The two's complement representation of -128 is 10000000, thus your results are correct.



回答2:

10000000 is -128
10000001 is -127
10000010 is -126
...

So 10000000 is not 0. It is -128 which was your output.



回答3:

This program

System.out.println(Integer.toBinaryString(-64));
System.out.println(Integer.toBinaryString(-64 << 1));
System.out.println("-64 << 1 = " + (-64 << 1));

prints

11111111111111111111111111000000
11111111111111111111111110000000
-64 << 1 = -128

You can see that -64 << 1 is the same as -64 except all the bits have been shift left by 1 (the lowest bit becomes a 0)



回答4:

In two's complement, the MSB is not just a sign bit, you're thinking ones'-complement maybe? In 8 bit two complement,

10000000 = 0x80 = -128



回答5:

In shift operators sign bit is ignored. So 1 1000000 << 1 is 10000000 which is -128.what's the problem?
Our machines are using two's complement to represent numbers (signed and unsigned). For representing a negative number machine negates it's positive and adds 1.
-128 is !10000000 + 1 = 01111111 + 1 = 10000000
EDIT:
I was wrong, only right shift operator's ignoring the sign bit. 10100000 << 1 == 01000000
For unsigned right shifting there's an operator >>> which shifts sign bit too.
11000000>>1 == 10100000 and 11000000>>>1 == 01100000



回答6:

<< means multiply by 2

>> means divide by 2

And, during shift operations don't consider signed bit.



回答7:

I’m wondering. << 1 (ignoring all details) is “multiply with 2.” -64 * 2 = -128. So why are you wondering that it indeed is -128?