-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;
}

It's an exercise I found on my book, but I really don't get It!

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
DarioDP
  • 627
  • 2
  • 9
  • 24
  • Which specific part do you have a question about? – Carl Norum Jan 09 '13 at 18:32
  • It returns an `int`. The exact value depends on the argument passed to the function. – moooeeeep Jan 09 '13 at 18:35
  • @CarlNorum, I don't get what this part does: c = (n & 0x01)? c+1: c; – DarioDP Jan 09 '13 at 18:37
  • 1
    To figure this out, take each piece of the function and make sure you understand it. The function is simple enough that you could "run" it on a piece of paper, which should help your understanding. – prprcupofcoffee Jan 09 '13 at 18:37
  • @user1100421, I address that in my answer below. – Carl Norum Jan 09 '13 at 18:38
  • Just a note that this function will loop once for each bit position in `n`, even if they are all zero. Other functions will only loop once for each bit actually set. See [How to count the number of bits set in a 32-bit integer?](http://stackoverflow.com/a/109036/597607). – Bo Persson Jan 09 '13 at 20:15
  • possible duplicate of [How to count the number of set bits in a 32-bit integer?](http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer) – t0mm13b Jan 10 '13 at 01:00

2 Answers2

7

It counts the number of bits set in the passed in parameter n (assuming your machine has 8-bit bytes). I'll comment inline with your code (and fix the terrible formatting):

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'
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
-1

It is doing a bitwise and - turning on bits off and off bits on.

Michael Thamm
  • 131
  • 1
  • 6