2013-01-09 144 views
-1
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函数返回什么?

+0

您对哪个特定部分有疑问? –

+0

它返回一个'int'。确切的值取决于传递给函数的参数。 – moooeeeep

+0

@CarlNorum,我没有得到什么。这部分工作: C =(N 0×01)? c + 1:c; – AshleyT

回答

7

它计算在参数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' 
} 
+0

谢谢! :)你不可能更清楚! :) – AshleyT

-1

它是做一个按位和 - 打开断和断位的位。

+2

不,这不是它在做什么。 –

+1

按位“和”操作不“上打开位关闭和关闭位”。这是一个“不”操作。 – Haz

+0

对 - 我应该只是运行代码来看看。谢谢。 –