What does the following C function compute?
int foo (int n)
{
int k = 0;
int t;
while (t = n & -n) {
++k;
n &= ~t;
}
return k;
}
— ADVERTISMENT—
—Advertise Here—
Home » EQ #1
What does the following C function compute?
int foo (int n)
{
int k = 0;
int t;
while (t = n & -n) {
++k;
n &= ~t;
}
return k;
}
This function counts the number of ones in the binary representation of the input argument. The expression n & -n has at most one bit set—in the position of the least-significant “one” in n— which is the only bit that a number and its two’s-complement negation have in common.
Each iteration of the loop identifies one “one” bit in n, and then the expression n &= ~t clears that bit for the next iteration. The variable k counts how many times this occurs.
Keep up-to-date with our FREE Weekly Newsletter!
Don't miss out on upcoming issues of Circuit Cellar.
— ADVERTISMENT—
—Advertise Here—
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.