Fast Bit Counting(未完成)

转自: http://gurmeet.net/puzzles/fast-bit-counting-routines/

 

#include <bitset> #include <iostream> // 0x 00001000 8 // 0x 00000111 7 // 0x 00000110 6 // 0x 00000101 5 // 0x 00000100 4 // 0x 00000011 3 // 0x 00000010 2 // 0x 00000001 1 // 0x 00000000 0 // [0, 255] for unsigned char's range unsigned char hex_table[256] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; char bit_count0(unsigned char ch) { char counter = 0; while (ch) { counter += ch & 0x00000001; ch >>= 1; } return counter; } char bit_count1(unsigned char ch) { char counter = 0; while (ch) { ++counter; ch &= ch - 1; } return counter; } char bit_count2(unsigned char ch) { char counter = 8 * sizeof(unsigned char); counter ^= sizeof(unsigned char) - 1; while (ch) { --counter; ch &= ch - 1; } return counter; } char bit_count3(unsigned char ch) { return hex_table[ch]; } int main (int argc, char * const argv[]) { int ch = 8; std::bitset<8> bs(ch); std::cout << bs << std::endl; printf("%d/n", bit_count0(ch)); printf("%d/n", bit_count1(ch)); printf("%d/n", bit_count2(ch)); printf("%d/n", bit_count3(ch)); return 0; } 

你可能感兴趣的:(Fast Bit Counting(未完成))