Bit Counter

int n;
n&077, here 077 = 00..0 111 111, so “bitwise and” sets zero all but the low-order 6 bits of n.

int bitcounter (unsigned x)
{
int b;
for (b=0; x!=0; x >>=1) //x>>1, but after first loop x = x, then x=x>>1 after that.
if (x&01)
b++;
}

int bitcounter (unsigned x)
{
int b=0;
while (x !=0)
{
b++;
x &= (x-1) //delete the rightmost 1-bit in x;
return b;
}

Leave a Reply