Reading Note One: Finding the number of 1 in a binary number

Source: Internet
Author: User

Problem Description:

For unsigned integer variables of one byte (8bit), the number of "1" in the second binary representation is required, which requires the efficiency of the algorithm to be executed as efficiently as possible.

In the process of writing programs, depending on the actual application, the requirements for storage space or efficiency are different. For example, on the PC and on the embedded device programming, there is a big difference.

Analysis and Solution:

Solution One:

Give a eight-bit binary example to analyze. For binary operations, we know that by dividing by one 2, the original number will be reduced by one 0. If there is more than one process, then there is a 1 in the current position.

Take 10100010 as an example:

The first time divided by 2 o'clock, the quotient is 1010001, the remainder is 0.

The second time divided by 2 o'clock, the quotient is 101000, the remainder is 1.

Therefore, it is possible to consider the use of Integer data division, by dividing and judging the value of the remainder to analyze.

1 intBitcount (unsignedintN)2 {3Unsignedintc =0;//counter4      while(n)5     {6         if(n% 2 = =1)//the current bit is 17C + +;//counter plus 18n = n/2;9     }Ten     returnC; One}

Solution two: Using bit manipulation

Reading Note One: Finding the number of 1 in a binary number

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.