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:
and also some Wikipedia pages:
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.
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) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With