How to count the number of trailing zeros of an integer? The simplest way is
to use the built-in function __builtin_ctz()
:
uint64_t count(uint64_t n) {
return __builtin_ctz(n);
}
What will happen if we don't have __builtin_ctz()
? If we have another
built-in function __popcount()
, which can compute the Hamming weight
(the number of set bits), then we can compute the number of trailing zeros with:
uint64_t count(uint64_t n) {
return __popcount((n & -n) - 1);
}
Note: Assume that two's complement is adopted for negation and substract,
the expression (n & -n)
will leave only the last set-bit in the input
integer. Next, the -1
operation will set the bits lower than the last
set-bit. And finally, you can get the number of trailing zeros with
__popcount()
.
Reference
- Wikipedia: Find First Set (retrived on 2014/12/17)