Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 981
Ande Turner Avatar asked Jul 07 '09 13:07

Ande Turner


People also ask

How do you know if a bit is 0 or 1?

Bitwise AND Operator (&) is a binary operator, which operates on two operands and checks the bits, it returns 1, if both bits are SET (HIGH) else returns 0. Here, NUM is the number whose bit you want to check and N is the bit number, (1<<N) SET the particular bit at Nth position.

How do you check bit is set or not in Java?

Method 1 (Using Left Shift Operator) 1) Left shift given number 1 by k-1 to create a number that has only set bit as k-th bit. temp = 1 << (k-1) 2) If bitwise AND of n and temp is non-zero, then result is SET else result is NOT SET.

How do you check if all even bits are 1?

Determine if all even place bits (counting from left to right) are set to 1. For instance, 0101 0101 would count whereas 1011 1000 would not count. If the the bit has 1's in all even places, return 1, or else return 0.

Which Bitwise operator is used for checking whether a bit is on or off?

Bitwise AND operator. 00001000, which is equal to 8 in decimal. decides whether the bit was ON or OFF.


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

like image 161
Jon Skeet Avatar answered Sep 16 '22 20:09

Jon Skeet


Another alternative:

if (BigInteger.valueOf(value).testBit(x)) {     // ... } 
like image 43
finnw Avatar answered Sep 18 '22 20:09

finnw