I have a uint64_t
and I would like to find the index of the first set bit, reset it to zero and find the next set bit.
How do I know when to terminate? BSF
The simplest would be to just check the input:
while (input) {
int32_t index = __builtin_ffsll(input);
// do stuff
}
More complicatedly, according to the docs the docs:
— Built-in Function:
int __builtin_ffs (int x)
Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.
Which lets you do:
for (int index = __builtin_ffsll(input);
index;
index = __builtin_ffsll(input))
{
// do stuff
}
Which accomplishes the same thing, you just have to repeat the __builtin_ffsll
call, so it's more verbose and in my opinion doesn't contribute to clarity.
2 points to keep in mind when using __builtin_ffs
:
while (m) {
// Get the rightmost bit location.
int BitOffset = __builtin_ffs(m);
// Clear the bit before the next iteration.
// Used in the loop condition.
m = (m >> BitOffset) << BitOffset;
// Do your stuff .....
}