Search code examples
cbit-manipulationbitwise-operatorsbitwise-and

Unable to determine the reasoning behind a bitwise operation


I have a function called aFunc() and it is doing some bitwise operations. I understand what the program is doing, but I'm unable to determine what's the reason for doing this. I passed this function values from 0 to 49, but I still cannot summarize the purpose of this function. Do you have any suggestions on what this function is doing? It's definitely not 1's or 2's complement.

int afunc( unsigned int i ) {
    int c = 0;
    while( i ) {
        if( i & 1 ) { c++; }
        i >>= 1;
    }
    return c;
}

for (int i = 0; i < 50; i++)
{   
    printf("%d returns %d.\n", i, afunc(i));
}  

Output below:

0 returns 0.
1 returns 1.
2 returns 1.
3 returns 2.
4 returns 1.
5 returns 2.
6 returns 2.
7 returns 3.
8 returns 1.
9 returns 2.
10 returns 2.
11 returns 3.
12 returns 2.
13 returns 3.
14 returns 3.
15 returns 4.
16 returns 1.
17 returns 2.
18 returns 2.
19 returns 3.
20 returns 2.
21 returns 3.
22 returns 3.
23 returns 4.
24 returns 2.
25 returns 3.
26 returns 3.
27 returns 4.
28 returns 3.
29 returns 4.
30 returns 4.
31 returns 5.
32 returns 1.
33 returns 2.
34 returns 2.
35 returns 3.
36 returns 2.
37 returns 3.
38 returns 3.
39 returns 4.
40 returns 2.
41 returns 3.
42 returns 3.
43 returns 4.
44 returns 3.
45 returns 4.
46 returns 4.
47 returns 5.
48 returns 2.
49 returns 3.

Solution

  • The program is counting the number of 1 bits in the given integer.

    0 = b0000 => 0 one bits
    1 = b0001 => 1 one bits
    2 = b0010 => 1 one bits
    ...
    

    Only the lower 4 bits shown for brevity.