v & 1
is 1 if the lowest bit in v
is set, and 0 if it's not.
The loop keeps dividing shifting the bits of v
right by 1 place each iteration, and thus the lowest bit of v
loops over each of the bits in the original v
(as each one gets to the 1's place before "falling off" the fractional end).
Thus, it loops over each bit and adds 1 to c if it's set, and adds 0 if it's not, thus totaling the set bits in the original v.
For example, with a starting v
of 1011
:
1011 & 1 = 1
, so c is incremented to 1.
- Then
1011
is shifted to become 101
.
101 & 1 = 1
, so c is incremented to 2.
101
is shifted to become 10
.
10 & 1 = 0
, so c isn't incremented and remains 2.
10
is shifted to become 1
.
1 & 1 = 1
, so c is incremented to 3.
1
is shifted to become 0
(because the last bit fell off the fractional end).
- Since the condition of the
for
loop is just v
, and v is now 0, which is a false value, the loop halts.
End result, c = 3, as we desire.