Java: Checking if a bit is 0 or 1 in a long

Viewed 84870

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?

14 Answers

I'd use:

if ((value & (1L << x)) != 0)
{
   // The bit was set
}

(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)

Another alternative:

if (BigInteger.valueOf(value).testBit(x)) {
    // ...
}

I wonder if:

  if (((value >>> x) & 1) != 0) {

  }

.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.

Tom Hawtin - tackline Jul 7 at 14:16

You can also use

bool isSet = ((value>>x) & 1) != 0;

EDIT: the difference between "(value>>x) & 1" and "value & (1<<x)" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).

In that particular case, with "(value>>x) & 1" you will have the sign of value, whereas you get a 0 with "value & (1<<x)" (it is sometimes useful to get the bit sign if x is too large).

If you prefer to have a 0 in that case, you can use the ">>>" operator, instead if ">>"

So, "((value>>>x) & 1) != 0" and "(value & (1<<x)) != 0" are completely equivalent

For the nth LSB (least significant bit), the following should work:

boolean isSet = (value & (1 << n)) != 0;

The value of the 2^x bit is "variable & (1 << x)"

Related