首页 > 代码库 > 计算二进制中1的个数

计算二进制中1的个数

 1 #include<iostream>
 2 using namespace std;
 3 int func1(unsigned int i) {
 4 
 5     unsigned int temp = i;
 6 
 7     temp = (temp & 0x55555555) + ((temp & 0xaaaaaaaa) >> 1);
 8 
 9     temp = (temp & 0x33333333) + ((temp & 0xcccccccc) >> 2);
10 
11     temp = (temp & 0x0f0f0f0f) + ((temp & 0xf0f0f0f0) >> 4);
12 
13     temp = (temp & 0x00ff00ff) + ((temp & 0xff00ff00) >> 8);
14 
15     temp = (temp & 0x0000ffff) + ((temp & 0xffff0000) >> 16);
16 
17     return temp;
18 
19 }
20 int func2(unsigned int i)
21 {
22     int count=0;
23     while (i)
24     {
25         count++;
26         i = i&(i - 1);
27     }
28     return count;
29 }
30 int main()
31 {
32     cout << func1(0x11530828) << endl;
33     cout << func2(0x11530828) << endl;
34     system("pause");
35     return 0;
36 }

 

计算二进制中1的个数