long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/
posted @ 2010-03-13 23:19 Little Snail 阅读(19) 评论(0) 编辑
B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111
The best method for counting bits in a 32-bit integer v is the following:
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
| B[0] = 0x55555555 = 01010101 01010101 01010101 01010101 | |||||||||
| B[1] = 0x33333333 = 00110011 00110011 00110011 00110011 | |||||||||
| B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111 | |||||||||
| B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111 | |||||||||
| B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111 | |||||||||
| The best method for counting bits in a 32-bit integer v is the following: | |||||||||
| v = v - ((v >> 1) & 0x55555555); // reuse input as temporary | |||||||||
| v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp | |||||||||
| c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count | 1 | ||||||||
| 01010101 | 01010101 | 01010101 | 01010101 | ||||||
| v= | 00000111 | ||||||||
| v >> 1 | 00000011 | ||||||||
| ((v >> 1) & 0x55555555) | 00000000 | 00000000 | 00000000 | 00000001 | |||||
| 11111111 | 11111111 | 11111111 | 11111111 | ||||||
| v = v - ((v >> 1) & 0x55555555); | 10000000 | 00000000 | 00000000 | 00000110 | |||||
| 00110011 | 00110011 | 00110011 | 00110011 | ||||||
| (v & 0x33333333) | 00000000 | 00000000 | 00000000 | 00000010 | |||||
| ((v >> 2) & 0x33333333); | 00000001 | ||||||||
| 00000011 | 0x1010101 | ||||||||
| 00000001000000010000000100000001 | |||||||||
| 00000001000000010000000100000001 | |||||||||
| c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count | 00000011 | ||||||||
posted @ 2010-03-13 21:43 Little Snail 阅读(22) 评论(0) 编辑

