Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if only one single bit is set within an integer (whatever its position)

I store flags using bits within a 64-bits integer.
I want to know if there is a single bit set whatever the position within the 64-bits integer (e.i. I do not care about the position of any specific bit).

boolean isOneSingleBitSet (long integer64)
{
   return ....;
}

I could count number of bits using the Bit Twiddling Hacks (by Sean Eron Anderson), but I am wondering what is the most efficient way to just detect whether one single bit is set...

I found some other related questions:

  • (8051) Check if a single bit is set
  • Detecting single one-bit streams within an integer

and also some Wikipedia pages:

  • Find first one
  • Bit manipulation
  • Hamming weight

NB: my application is in java, but I am curious about optimizations using other languages...


EDIT: Lưu Vĩnh Phúc pointed out that my first link within my question already got the answer: see section Determining if an integer is a power of 2 in the Bit Twiddling Hacks (by Sean Eron Anderson). I did not realized that one single bit was the same as power of two.

like image 830
oHo Avatar asked Nov 16 '12 16:11

oHo


1 Answers

If you just literally want to check if one single bit is set, then you are essentially checking if the number is a power of 2. To do this you can do:

if ((number & (number-1)) == 0) ...

This will also count 0 as a power of 2, so you should check for the number not being 0 if that is important. So then:

if (number != 0 && (number & (number-1)) == 0) ...
like image 169
Neil Coffey Avatar answered Sep 30 '22 08:09

Neil Coffey