J
jacklisp
When I do the exercises I met a question:
In a two's complement number system, x &= (x-1) deletes the rightmost
1-bit in x. Explain why. Use this observation to write a faster
version of bitcount.
The old version of bitcount function as follows:
/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}
I had consider for a long time still fetch the point,
how can I re-write the "new & faster" bitcount function?
Any suggestion?
Thanks.
In a two's complement number system, x &= (x-1) deletes the rightmost
1-bit in x. Explain why. Use this observation to write a faster
version of bitcount.
The old version of bitcount function as follows:
/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}
I had consider for a long time still fetch the point,
how can I re-write the "new & faster" bitcount function?
Any suggestion?
Thanks.