I have the following function, witch gets an integer (decimal number)and return the number of ones of this integer after convert it to binary, (e.g. if we pass 6 the function will return 2 because 6 in decimal equal to 110 in binary).
that’s nice, but unfortunately I can not understand how it’s work. The code is:
int number_of_ones(int i){
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
is there any one can explain to me how it works?
It’s an algorithm to count the number of bits set to one without branching. It is described here:
http://graphics.stanford.edu/~seander/bithacks.html