I have the following function for counting the number of one bits:
/** Count the number of 1 bits in num */
int bitcount(int num)
{
unsigned i = 0;
int count = 0;
for(; num != 0; num = num >> 1)
{
if(num & 1)
{
count++;
}
}
return count;
}
It works fine, however the book I am reading (K&R) says that there is a faster version of bitcount that relies on the fact that in a two's complement number system, x &= (x - 1)
deletes the rightmost bit in x. I need help leveraging this information to create a faster bitcount algorithm.