数32位 unsigned int中1的个数

时间:2023-03-09 13:12:16
数32位 unsigned int中1的个数

参考文章:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

最简单的方法:

int BitCount0(unsigned int n)
{
unsigned int c = ; // 计数器
while (n >)
{
if((n &) ==) // 当前位是1
++c ; // 计数器加1
n >>= ; // 移位
}
return c ;
}

消除统计法

int BitCount2(unsigned int n)
{
unsigned int c = ;
for (c =; n; ++c)
{
n &= (n -) ; // 清除最低位的1
}
return c ;
}

8bit查表法

 unsigned int table[] =
{
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
};
int BitCount2(unsigned int n)
{
char * b = (char *)&n;
return b[]+b[]+b[]+b[];
}

巧妙转换法

int BitCount3(unsigned int n)
{
n = (n &0x55555555) + ((n >>) &0x55555555) ;
n = (n &0x33333333) + ((n >>) &0x33333333) ;
n = (n &0x0f0f0f0f) + ((n >>) &0x0f0f0f0f) ;
n = (n &0x00ff00ff) + ((n >>) &0x00ff00ff) ;
n = (n &0x0000ffff) + ((n >>) &0x0000ffff) ; return n ;
}

#include <stdio.h>

typedef unsigned int UINT32;
const UINT32 m1  = 0x55555555;  // 01010101010101010101010101010101
const UINT32 m2  = 0x33333333;  // 00110011001100110011001100110011
const UINT32 m4  = 0x0f0f0f0f;  // 00001111000011110000111100001111
const UINT32 m8  = 0x00ff00ff;  // 00000000111111110000000011111111
const UINT32 m16 = 0x0000ffff;  // 00000000000000001111111111111111
const UINT32 h01 = 0x01010101;  // the sum of 256 to the power of 0, 1, 2, 3

int popcount_2(UINT32 x)
{
x -= (x >> ) & m1; //put count of each 2 bits into those 2 bits
x = (x & m2) + ((x >> ) & m2); //put count of each 4 bits into those 4 bits
x = (x + (x >> )) & m4; //put count of each 8 bits into those 8 bits
x += x >> ; //put count of each 16 bits into their lowest 8 bits
x += x >> ; //put count of each 32 bits into their lowest 8 bits
return x & 0x1f;
}
inline short popcount_3(UINT32 x)
{
x -= (x >> ) & m1; //put count of each 2 bits into those 2 bits
x = (x & m2) + ((x >> ) & m2); //put count of each 4 bits into those 4 bits
x = (x + (x >> )) & m4; //put count of each 8 bits into those 8 bits
return (x * h01) >> ; // left 8 bits of x + (x<<8) + (x<<16) + (x<<24)
}
//除了指令法,这种最快

指令法

//sse - 4,编译时加入 -msse4[相当于4.1 + 4.2]
#include<nmmintrin.h>
unsigned int n = ;
unsigned int bitCount = _mm_popcnt_u32(n) ;

关于sse有一个很好的学习资料,各个sse版本里的函数及其功能!http://blog.****.net/fengbingchun/article/details/18460199

相关文章