-5

Why does -1 << 23 and -1 << 55 return the same value in Java? It seems they should be very different, as I'm shifting by a lot more places! However, they result in the same value. Why does this happen?

public class BitShifting {
  public static void main(String... args) {
    long foo = -1 << 23;
    long bar = -1 << 55;

    System.out.println(foo);
    System.out.println(bar);
  }
}

Output:

-8388608
-8388608
2
  • Ah crap, missed that. Thanks @AndyBrown
    – durron597
    Jan 30, 2015 at 16:12
  • Compare it with -1L << 55 and -1L >>> -1 for interest. Jan 30, 2015 at 16:36

1 Answer 1

5

Because 1 is an int, not a long, and the conversion to long doesn't happen until after the assignment statement. Java will notice that the left hand argument is an int and not a long, and will round the right hand value accordingly.

From the JLS:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

The behavior will be as expected if the left hand argument is declared with 1L, as below:

public class BitShifting {
  public static void main(String... args) {
    long foo = -1L << 23;
    long bar = -1L << 55;

    System.out.println(foo);
    System.out.println(bar);
  }
}

Output:

-8388608
-36028797018963968
3
  • 4
    Not really seeing the value in posting Yet Another Question (we have lots of them here) about not realizing that numeric literals in Java are ints if you already know the answer. Yes, asking and answering your own question is fine, but if it's very-well-covered ground, I'm not seeing the point. Jan 30, 2015 at 16:04
  • 1
    @T.J.Crowder The interesting part is that the right hand operand gets masked, not that numeric literals are ints
    – durron597
    Jan 30, 2015 at 16:05
  • 4
    I'd suggest using 1L instead of 1l for readability Jan 30, 2015 at 16:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.