/*
解法一
将二进制数的各位相加,结果即为1的个数。从两位二进制开始计算。
55555555 h = 01010101010101010101010101010101 b
33333333 h = 00110011001100110011001100110011 b
0f0f0f0f h = 00001111000011110000111100001111 b
00ff00ff h = 00000000111111110000000011111111 b
0000ffff h = 00000000000000001111111111111111 b
1) 奇偶位相加 2) 2位一组相加 3) 4位为一组相加 4) 8位为一组相加 ..
00->00 0001->0001
01->01 0101->0010
10->01 0110->0011
11->10 1010->0100
*/
unsigned long func(unsigned long x)
{
x = (x & 0x55555555UL) + ((x >> 1) & 0x55555555UL);
x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
x = (x & 0x0f0f0f0fUL) + ((x >> 4) & 0x0f0f0f0fUL);
x = (x & 0x00ff00ffUL) + ((x >> 8) & 0x00ff00ffUL);
x = (x & 0x0000ffffUL) + ((x >> 16) & 0x0000ffffUL);
return x;
}
/*
解法二
若
n = XXXXXX10000 b
n-1 = XXXXXX01111 b
n & n-1 = XXXXXX00000 b
将最低位起遇到的第一个1置零,计数器加1
*/
int bit_count(unsigned int n)
{
int count;
for(count = 0; n; n &= n - 1)
{
count++;
}
return count;
}
解法一
将二进制数的各位相加,结果即为1的个数。从两位二进制开始计算。
55555555 h = 01010101010101010101010101010101 b
33333333 h = 00110011001100110011001100110011 b
0f0f0f0f h = 00001111000011110000111100001111 b
00ff00ff h = 00000000111111110000000011111111 b
0000ffff h = 00000000000000001111111111111111 b
1) 奇偶位相加 2) 2位一组相加 3) 4位为一组相加 4) 8位为一组相加 ..
00->00 0001->0001
01->01 0101->0010
10->01 0110->0011
11->10 1010->0100
*/
unsigned long func(unsigned long x)
{
x = (x & 0x55555555UL) + ((x >> 1) & 0x55555555UL);
x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
x = (x & 0x0f0f0f0fUL) + ((x >> 4) & 0x0f0f0f0fUL);
x = (x & 0x00ff00ffUL) + ((x >> 8) & 0x00ff00ffUL);
x = (x & 0x0000ffffUL) + ((x >> 16) & 0x0000ffffUL);
return x;
}
/*
解法二
若
n = XXXXXX10000 b
n-1 = XXXXXX01111 b
n & n-1 = XXXXXX00000 b
将最低位起遇到的第一个1置零,计数器加1
*/
int bit_count(unsigned int n)
{
int count;
for(count = 0; n; n &= n - 1)
{
count++;
}
return count;
}