Bit-shifting in Java

0

Why is it that:

return 1 | (1 << 32) // returns 0x00000001

but:

return 6 | (1 << 32) // returns 0x00000007

I was expecting the latter to return 0x00000006. What type of bitmask can be OR-ed with the expression to generate 0x00000006 for 6 | (1 << 32)?

java
bit-manipulation
asked on Stack Overflow Oct 17, 2014 by syker • edited Oct 17, 2014 by syker

1 Answer

5

Java only uses the last 5 bits of the bit-shift argument when shifting ints. So 1 << 32 is equivalent to 1 << 0, or just 1.

The 1 bit is already set in 1, so 1 | 1 is 1. Only the last 8 bits shown for clarity:

   0000 0001 (1)
or 0000 0001 (1)
------------
   0000 0001 (1)

But the 1 bit is not set in 6, so 6 | 1 sets the bit and the number becomes 7. It's working as expected.

   0000 0110 (6)
or 0000 0001 (1)
------------
   0000 0111 (7)

Addition

In response to the addition to the question:

6 has only 2 bits set (0000 0110), so any number that you could bitwise-OR with 6 and still have 6 must have all bits clear that are clear in 6. That leaves just 4 choices, combinations of the set bits of 6 being set or cleared:

  • 0 (0000 0000)
  • 2 (0000 0010)
  • 4 (0000 0100)
  • 6 (0000 0110)

Any other int will set at least one other bit, making the output something other than 6.

answered on Stack Overflow Oct 17, 2014 by rgettman • edited Oct 17, 2014 by rgettman

User contributions licensed under CC BY-SA 3.0