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

Solution 1:

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.)

Solution 2:

Another alternative:

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

Solution 3:

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