This program is supposed to determine how many units are stored in the value of the variable c_val, if each unit is stored as a set bit.
My question is: why did the author write if (c % 2 == 1) count++; then shift c to the right with this statement c = c >> 1;?
#include <stdio.h>
#include <cstdlib>
int main(){
unsigned char c_val;
printf("char value = ");
scanf("%c", &c_val);
int count = 0;
unsigned char c = c_val;
while(c){
if (c % 2 == 1) count++;
c = c >> 1;
}
printf("%d bits are set", count);
system("pause");
}
The data size of type char is always one byte – no exceptions. This code, however, calculates the popcount – that is, the number of 1 bits – in
c_val.We can translate the relevant code from
to
The last change I made works because right-shifting an unsigned integral data type (in this case,
unsigned char) is equivalent to dividing by 2, with round-toward-zero semantics.We can think of
cas a conveyor belt of bits – zero bits come in from the left, and one bit falls off the right on each loop iteration. If the rightmost bit is a 1, we increase the count by 1, and otherwise the count remains unchanged. So, oncecis filled with zero bits, we know that we have counted all the one bits, and exactly the one bits, socountcontains the number of one bits inc_val.