popcnt.cpp
| 1 |
static const unsigned char g_pop_cnt[256] = |
|---|---|
| 2 |
{
|
| 3 |
# define B2(n) n, n+1, n+1, n+2 |
| 4 |
# define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) |
| 5 |
# define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) |
| 6 |
B6(0), B6(1), B6(1), B6(2) |
| 7 |
}; |
| 8 |
|
| 9 |
static unsigned int POPCNT_Table(const unsigned char * buf, unsigned int len) { |
| 10 |
unsigned int cnt = 0; |
| 11 |
unsigned int ndwords = len / 4; |
| 12 |
for(; ndwords; ndwords--) {
|
| 13 |
unsigned int v = *(unsigned int*)buf; |
| 14 |
cnt += g_pop_cnt[v & 0xff] +
|
| 15 |
g_pop_cnt[(v >> 8) & 0xff] + |
| 16 |
g_pop_cnt[(v >> 16) & 0xff] + |
| 17 |
g_pop_cnt[v >> 24];
|
| 18 |
buf += 4;
|
| 19 |
} |
| 20 |
if (len & 2) { |
| 21 |
unsigned int v = *(short*)buf; |
| 22 |
cnt += g_pop_cnt[ v & 0xff ] +
|
| 23 |
g_pop_cnt[ v >> 8 ];
|
| 24 |
buf += 2;
|
| 25 |
} |
| 26 |
if (len & 1) |
| 27 |
cnt += g_pop_cnt[ *buf ]; |
| 28 |
return cnt;
|
| 29 |
} |
| 30 |
|
| 31 |
int main(int argc, char const *argv[]) |
| 32 |
{
|
| 33 |
unsigned int value = 1; |
| 34 |
for (unsigned int i = 0; i < 262151000; i++) { |
| 35 |
unsigned int res = POPCNT_Table((unsigned char*)&i, 4); |
| 36 |
} |
| 37 |
return 0; |
| 38 |
} |