user4252523
user4252523

Reputation: 69

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.

Upvotes: 1

Views: 60

Answers (2)

S.S. Anne
S.S. Anne

Reputation: 15584

It counts the number of set bits in an integer.

Let's step through it.

Counter:

int c = 0;

Loop; while i has bits set (or is true) continue:

while( i ) {

If the low bit of i is set, increment the counter:

    if( i & 1 ) { c++; }

shift i right by one to go on to the next bit; if i is zero after this, there are no more bits set:

    i >>= 1;

end of loop:

}

return the number of set bits:

return c;

Upvotes: 2

kaylum
kaylum

Reputation: 14044

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.

Upvotes: 3

Related Questions