"C Language" methods: the decimal number into a binary number, to calculate the number of 1 __c language

Source: Internet
Author: User

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++;
}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.