Uzumaki Ichigo Uzumaki Ichigo - 1 month ago 5x
Java Question

java bitwise left shift on long

I have following code

long mask = 1;
mask = (long) (1 << 31);
System.out.println("mask " + mask );

I get

In binary it is

I do understand if it were an int, output would be -2147483648 as int is 32 bytes and shifting 1 to leftmost bit I would have got most negative number. But here I am using long, and output should be something positive


@Tunaki, the other question one that you marked as duplicate, is performing operation on int which I knew (as seen above) will produce that same incorrect result. My problem was with long. So it is not duplicate.


answer is also different in my case. On the other post answer tells to use long, here It is telling me what is wrong while I am using long and states issue with my incorrect type casting. That proves that it is not duplicate.


You are casting to long only after the bit-shift operation is performed on an int operand (1), which means you are casting -2147483648 to long, which gives you -2147483648.

You should write :

mask = 1L << 31;

In order to perform the operation on a long operand.

Output :

mask 2147483648