I have got a binary number of length 8 for eg 00110101
There are 8 bits set.
I need a fast bit count to determine the number of set bits, the popcount aka population count.
Running the algo like this x=x&(x-1)
will limit it to the number of set bits in the number contains but I am not very sure as to how to use it.
Unlike Count the number of set bits in a 32-bit integer, I only have 8-bit integers, so O(log width) bithack methods still have several steps and might not be better than O(set_bits) or 4-bit or 8-bit lookup tables on CPUs without hardware popcount, or if compiling in a way that can't take assume support.
This x=x&(x-1)
removes the lowest set bit from the binary string. If you count the number of times you remove the lowest bit before the number becomes 0, you'll get the number of bits that were set.
char numBits(char x){
char i = 0;
if(x == 0)
return 0;
for(i = 1; x &= x-1; i++);
return i;
}