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)));
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s an important thing to note about the line
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
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
longis 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