Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit shift operation does not return expected result

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)));
like image 346
Pier-Alexandre Bouchard Avatar asked Mar 26 '12 22:03

Pier-Alexandre Bouchard


1 Answers

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)
like image 157
Adam Mihalcin Avatar answered Oct 01 '22 11:10

Adam Mihalcin