int f(int n)
{
int i, c = 0;
for (i=0; i < sizeof(int)*8; i++, n >>= 1)
c = (n & 0x01)? c+1: c;
return c;
}
这是我在书上找到的一个练习,但我真的不明白!
它计算传入参数中设置的位数n
(假设您的机器有 8 位字节)。我将在您的代码中内联注释(并修复糟糕的格式):
int f(int n)
{
int i; // loop counter
int c = 0; // initial count of set bits is 0
// loop for sizeof(int) * 8 bits (probably 32),
// downshifting n by one each time through the loop
for (i = 0; i < sizeof(int) * 8; i++, n >>= 1)
{
// if the current LSB of 'n' is set, increment the counter 'c',
// otherwise leave it the same
c = (n & 0x01) ? (c + 1) : c;
}
return c; // return total number of set bits in parameter 'n'
}
它正在按位进行 - 打开位并关闭位。