I am studying for an interview and I came across an interview that asks to count the number of bits in an int. I have the solution but I do not uderstand either solution. Woul somebody please explain it to me? Thanks
Code:
int bitcount(int v)
{
for(int count=0; v; count++, v &= ~(v-1));
return count;
}
int table[] = {0,1,1,2,1,2,2,3, 1,2,2,3,2,3,3,4 };
#define bc(x) table[(x)&0xf ] // maps nibbles to number of bits
int bitcount(int v)
{
// assume 16 bit int
return bc(x) + bc(x>>4) + bc(x>>8) + bc(x>>12);
}