I was trying to learn more about bits, and I came across this example.
How does this code work to count the bits? (My C is very rusty, by the way).
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; v >>= 1)
{
c += v & 1;
}
v & 1is 1 if the lowest bit invis set, and 0 if it’s not.The loop keeps dividing shifting the bits of
vright by 1 place each iteration, and thus the lowest bit ofvloops over each of the bits in the originalv(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
vof1011:1011 & 1 = 1, so c is incremented to 1.1011is shifted to become101.101 & 1 = 1, so c is incremented to 2.101is shifted to become10.10 & 1 = 0, so c isn’t incremented and remains 2.10is shifted to become1.1 & 1 = 1, so c is incremented to 3.1is shifted to become0(because the last bit fell off the fractional end).forloop is justv, and v is now 0, which is a false value, the loop halts.End result, c = 3, as we desire.