bit shift operation does not return expected resul

2020-02-26 10:51发布

问题:

Why does Java return -2147483648 when I bit shift 1 << 63 ?

The expected result is 9 223 372 036 854 775 808, tested with Wolfram Alpha and my calculator.

I tested:

System.out.print((long)(1 << (63)));

回答1:

There's an important thing to note about the line

System.out.print((long)(1 << (63)));

You first take (1 << 63), and then you cast to long. As a result, you are actually left-shifting in integers, so the long cast doesn't have any effect. That's why shifting 63 bits left gives the min integer rather than the min long.

But there's another, more important point. Java longs are always signed, so even the line

System.out.print(1L << 63);

would give a negative number. Under two's complement, whenever the leftmost bit is a 1 the number is negative.

You actually cannot represent the number 263 = 9223372036854775808 in a Java primitive type, because that number is bigger than the maximum long, and long is the largest primitive type. You can represent this number as a BigInteger, though. You can even generate it via a left-shift by 63 with the code

BigInteger.ONE.shiftLeft(63)


回答2:

You are having an integer overflow [twice].

1 << 32 == 1
1 << 31 == -2147483648 [ becuase this is the binary representation in 2's complement for -2147483648]
1 << 63 == 1 << (32 + 31) == (1 << 32) << 31 == 1 << 31 == -2147483648

When you do (long)(1 << (63)) you are only casting the result of 1 << (63) [which is -2147483648] to a long - and it does not change its value.