Here are three ways I've learned, and if you have a better way to talk about it.
First, we need to know how the decimal system is converted into binary, as shown below.
Get a 10 binary number of 1010
Then we'll find out that 10%2 is the last one to determine whether a binary number is 0 or 1, when the judgment is complete, move to the right one that is 10/2 to 5, and then 5%2 to determine whether the penultimate digit is 0 or 1, then move to the right after the judgment is 5/2 to 2 and repeat the process until 0/2 is over. Eventually we got a 10 binary number of 1010.
Based on the above thought, we can get a most preliminary algorithm.
while (data>0)
{
if (data%2==1)
{count++}
data = DATA/2;
}
But we can be a little more simple, as follows:
while (data>0)
{
if (data & 0x1) //with the lowest bit phase, the judgment is 0 or 1
{ count++;}
data = data>>1; Move 1-bit to the right
}
However, the two methods above are usually suitable for the low position of the 1 comparison concentration of binary number, for example: 101101
But if it's 1100000, it's going to waste a lot of time on the 0 ahead, and it's inefficient.
So, in order to improve efficiency, we introduce the following approach:
The "bitwise AND" method is the lowest bit of 1 borrow, the resulting value and the original phase, repeat the process until the result is 0.
This means that in this method, as long as there are 1 in the value, the process repeats.
The code is as follows:
while (data)
{
data = data & (data-1);
count++;
}