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)));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With