Test if a bitboard have only one bit set to 1 [duplicate]
Question
I have a bitboard and I want to check in C if there is ONLY one bit set to 1.
#include <stdint.h>
typedef uint64_t bboard;
bboard b = 0x0000000000000010;
if (only_one_bit_set_to_one (b)) // in this example expected true
// do something...
Any idea to write the function int only_one_bit_set_to_one (bboard b)
?
Solution
Sure, it's easy:
int only_one_bit_set_to_one (bboard b)
{
return b && !(b & (b-1));
}
Say b
has any bits set, the least significant is bit number k
. Then b-1
has the same bits as b
for indices above k
, a 0-bit in place k
and 1-bits in the less significant places, so the bitwise and removes the least significant set bit from b
. If b
had only one bit set, the result becomes 0, if b
had more bits set, the result is nonzero.
OTHER TIPS
This may be a bit naive, but I'd loop from 0 to 63, clear the relevant bit, and see if the result is 0:
if (b != 0) {
for (i = 0; i < 64; ++i) {
if (b & ~(1 << i)) == 0) {
return 1;
}
}
return 0;
}
it's nowhere near as clever as the other posted answers, but it has the advantage of being easy to understand.