Bit shift operation does not return the expected result

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

Expected Result: 9,223,372,036,854,775,808, tested with Wolfram Alpha and my calculator.

I tested:

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

+6
source share
2 answers

It’s important to mark the line here

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

First you take (1 << 63) , and then you throw to the end. As a result, you actually shift to the left in integers, so a long throw has no effect. Therefore, if you shift 63 bits to the left, the value of min will be minimal, not long.

But there is another, more important point. Java longs are always signed, so even a string

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

will give a negative number. Under two additions, when the leftmost bit is 1, the number is negative.

In fact, you cannot imagine the number 2 63 = 9223372036854775808 in the Java primitive type, because this number is larger than the maximum, and long is the largest primitive type. You can represent this number as BigInteger . You can even generate it with a left shift of 63 with the code

 BigInteger.ONE.shiftLeft(63) 
+27
source

You have integer overflow [twice].

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

When you execute (long)(1 << (63)) , you do the result 1 << (63) [which is -2147483648 ] by long - and it does not change its value.

+6
source

Source: https://habr.com/ru/post/911704/


All Articles