When the integer is expected to be dense, you have the corresponding trick
size_t count = sizeof(x) * 8;
while(x != -1) {
x |= x+1;
--count;
}
return count;
Re:The NSA Instruction (2019)
by throw5away on Friday June 11, 2021 @04:40PM
(#27478195)
This is essentially equivalent to feeding the input through bitwise-NOT first. Unfortunately, there are far more integers that are neither sparse nor dense than integers that are sparse or dense.
It's not that fast unless your integer is really sparse (since it has a branch), but I've always liked the bit hack.