Search code examples
javalong-integerbit-shiftbitset

Long getting treated as 32 bits in Java?


I am trying to run the following code,

public class MyClass {
    public static void main(String args[]) {
        long x = 1 << 39;
        long l = 537150415L;
        l = l | x;

        System.out.println(x);
        System.out.println(l);
    }
}

This outputs,

128
537150415

I was expecting x to be a large number. 128 looks like 2^7, which is 2^(39-32). But I thought long is 64 bits.

I am trying to make a bitset of numbers present in set. The numbers can be between 1-60.

JDoodle link - [https://www.jdoodle.com/online-java-compiler#&togetherjs=uH49U5c4Ej]


Solution

  • The problem is that 1 << 39 is a 32 bit expression. So

    long x = 1 << 39;
    

    first calculates a 32 bit value, then sign extends that to a 64 bit value for the assignment.

    If you want to create a 64 bit mask, use 1L << 39.