The beauty of programming reading notes: Find a Byte (8bit) of unsigned integer variable represented by the number of 1 in the binary

Source: Internet
Author: User
Tags integer division
#include <iostream> using namespace std;

typedef unsigned char BYTE; Reader:shizhixin//email:szhixin@gmail.com//blog:http://blog.csdn.net/shizhixin//date:2012-05-07// Function: The number of 1 in binary represented by an unsigned integer variable of one byte (8bit): Requires the algorithm to perform as efficiently as possible.
	(topics from the beauty of programming 2.1, the beauty of program reference programming)//Example://By Right shift and with the operation to get the number of 1 in bytes int getnumber1 (byte num) {int count=0;
		for (int i=0; i<8; i++) {if ((num>>i) & 0x01) = = 1) {count++;
} return count;
The code is modified on the basis of 1, the algorithm is the same, in contrast to 1, the if is changed to while,//The advantage is that the right move to the end is definitely 0, you can do the end of the loop, and the number of operations after///is not 1 is 0, so no if to determine whether to increase the count//complexity log (num)
	int getnumber2 (BYTE num) {int count=0;
		while (num) {count = num & 0x01;
	Num >>= 1;
return count;
//With an ingenious operation, V & (V-1) can eliminate the last 1 in binary notation each time,//Use this technique to reduce the number of loops.
	int getnumber3 (BYTE num) {int count=0;
		while (num) {num &= num-1;
	count++;
return count; //Space swap time, but does not fit the number of larger operations, such as DWORD int getnumber4 (BYTE num) {int looktable[256]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3 , 2,3,3,4,2,3, 3,4,3,4,4,5,1,2,2,3,2,3,3,4, 2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
			2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,
			4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
			2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,
			3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
	4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};
return Looktable[num];
	} void Main () {int num;
	cout<< "Please input a BYTE [0-255]" <<endl;
	cin>>num; 
		while (num < 0 | |-num > 255) {cout<< "please input a BYTE [0-255]" <<endl;
	cin>>num;
	} cout<< "Getnumber1 is:" <<getnumber1 ((BYTE) num) <<endl;
	cout<< "Getnumber2 is:" <<getnumber2 ((BYTE) num) <<endl;
        cout<< "Getnumber3 is:" <<getnumber3 ((BYTE) num) <<endl; cout<< "Getnumber4 is:" <<getNumber4 ((BYTE) num) <<endl; }

--------------------------------------------------------------------------------------------------------------- -------------------------------------

There is a better solution: "The beauty of programming" reading notes-"to find the number of binary 1"

http://blog.csdn.net/justpub/article/details/2292823


The beauty of programming--Microsoft technical interview experience, reading notes

"Find the number of 1 in a binary number"

by Zellux

From the Electronic Industry publishing House blog Point of View and the w3china.org community jointly held "look like chapter, write book review, to win the beauty of programming-Microsoft technical interview Experience" Activities ", please see: Http://bbs.w3china.org/dispbbs.asp?boardID =42&id=61162

Everybody enthusiastically participated in, the activity is very enthusiastic. The following article comes from the reader Zellux:

Find the number of 1 in the binary. For a variable of one byte (8bit), the number of "1" in the binary representation is required, and the execution efficiency of the algorithm is as high as possible.

Let's look at some of the algorithms given in the sample chapter:

Solution One , every time except two, see if it is odd, yes, the cumulative add one, and finally this result is the binary representation of the number of 1.

Solution two , the same use of a loop, but the operation of the inside with the displacement operation simplified.

1:int Count (int v)
2: {
3:int num = 0;
4:while (v) {
5:num + = v & 0x01;
6:v >>= 1;
7:}
8:return num;
9:}

solution three , with a clever and operation, V & (V-1) Each can eliminate the binary representation of the last 1, using this technique can reduce a certain number of cycles.

solution four , look-up table method, because only the data 8bit, directly build a table, containing the number of 1 of the numbers, and then check the table on the line. Complexity O (1).

1:int counttable[256] = {0, 1, 1, 2, 1, ..., 7, 7, 8};
2:
3:int Count (int v) {
4:return Counttable[v];
5:}

OK, here are the four options given in the sample chapter, and here's what I think.

The first is the measurement of the algorithm, complexity is really the only standard. Especially for this data size given, and very small case, complexity is actually a relatively minor factor.

The complexity of the tabular method is O (1), I use the solution one, the circulation eight times fixed, the complexity is also O (1). As for the size of the data to become 32-bit integral type, the look-up table method is not appropriate.

Secondly, I think since it is such a small operation, the scale of measurement is necessarily small, CPU clock cycle can be used as a reference.

There are several times integer additions in one of the solutions, several times integer division (the general compiler can optimize it to the displacement), there are several circular branches to judge, a few parity judgment (this time consuming, according to the Csapp data, a general branch penalty have to consume 14 or so cycle), Add up to about dozens of cycle.

Then look at the solution four, look-up table method appears to be the first address calculation can be solved, but in fact here to use an interview operation, and the first visit is very likely that the array is not in the cache, such a cache miss the result may be to consume dozens of or even hundreds of cycle (because to access memory). So for this "small operation", the performance of this algorithm is actually very poor.

Here I recommend several algorithms to solve this problem, taking 32-bit unsigned integer as an example.

1:int Count (unsigned x) {
2:x = X-((x >> 1) & 0x55555555);
3:x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
4:x = (x + (x >> 4)) & 0x0f0f0f0f;
5:x = x + (x >> 8);
6:x = x + (x >> 16);
7:return x & 0x0000003f;
8:}

Here is the binary, 221 groups Add, then four four a group added, then eight eight, and finally get everyone's sum.

And a more ingenious hakmem algorithm.

1:int Count (unsigned x) {
2:unsigned N;
3:
4:n = (x >> 1) & 033333333333;
5:x = X-n;
6:n = (n >> 1) & 033333333333;
7:x = X-n;
8:x = (x + (x >> 3)) & 030707070707;
9:x = Modu (x, 63);
10:return x;
11:}

First of all, the binary three a group, find out the number of 1 in each group, and then merge adjacent two groups, get six a group of 1 of the number, and finally very clever with the addition of 63 to obtain the results.

Because 2^6 = 64, that is to say, X_0 + x_1 * + x_2 * = x_0 + x_1 + x_2 (mod 63), where the equals sign is the same.

This program only needs about 10 instructions, and does not visit to save, fast.

Thus, to measure the actual effect of an algorithm depends not only on the complexity, but also the combination of other circumstances specific analysis.

On the next two extensions, the question is how to deal with the 32-bit integer, which has been said above.

The second question is given two integers a and B, asking how many bits A and B are different.

This problem is actually a number of 1 problems a step, as long as the first calculation of a and B of the difference or results, and then the value of the number of 1 on the line.

Overall this book is still very good, more like the inside for a problem to propose different algorithms and constantly improve the style. Here to put forward a little personal understanding, I hope everyone corrected  ;-)

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.