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;
}
这是一个练习,我在我的书中找到,但我真的不明白这一点!这个C函数返回什么?
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;
}
这是一个练习,我在我的书中找到,但我真的不明白这一点!这个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'
}
谢谢! :)你不可能更清楚! :) – AshleyT
它是做一个按位和 - 打开断和断位的位。
您对哪个特定部分有疑问? –
它返回一个'int'。确切的值取决于传递给函数的参数。 – moooeeeep
@CarlNorum,我没有得到什么。这部分工作: C =(N 0×01)? c + 1:c; – AshleyT