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

Ande Turner picture Ande Turner · Jul 7, 2009 · Viewed 74.3k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Jul 7, 2009

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