Search code examples
javalong-integerbit-shiftbitmasktilde

Why does a shifted integer mask with a tilde casted to a long return zero? (Java, bit shift)


I am trying to create a mask to view specific bits on a long in Java. I tried the following:

long mask = ~ (0xffffffff << 32);

If I print this on the console it will return 0 but I am expecting 4294967295 since my result should look like 0x00000000FFFFFFFFL and 2^32 - 1 equals 4294967295. When I shift a long mask it works but I do not understand why.

long mask = ~ (0xFFFFFFFFFFFFFFFFL << 32);

Can anyone explain me this behavior?


Solution

  • Java assumes that if you're performing arithmetic operations on ints, then you want to get an int back, not a long. (The fact that you assign the output to a long after the calculation is done does not affect the calculation itself.)

    Left-shifting an int (which is 32 bits) by 32 places does nothing. When you left-shift an int, only the five lowest-order bits of the right-hand operand are used, giving a number in the range 0 to 31.
    http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19

    That's why (0xffffffff<<32)==0xffffffff, and ~(0xffffffff<<32)==0

    When shifting a long (which is 64 bits), the six lowest-order bits are used, giving a number in the range 0 to 63.

    If you use 0xffffffffL, then Java will know to produce another long. So you can shift by 32 places without going off the left end of the number.