首页 > 其他 > 详细

计算二进制中1的个数

时间:2017-04-27 15:13:42      阅读:196      评论:0      收藏:0      [点我收藏+]
 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的个数

原文:http://www.cnblogs.com/wujufengyun/p/6774165.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!