There's also several popcount routines in the book Hacker's Delight. There's a 2nd Edition, but I've got the 1st in front of me. Chapter 5 has pages of algorithms and code to do this, apparently with tradeoffs between code size and speed. On page 71 is a fast-looking one that uses a 256-byte array with each entry being the number of bits at its address, and uses that for howevermany bytes of a word you need. Here's the gist:
Code: Select all
int pop (unsigned x)
{
Static char table[256] = {0, 1, 1, 2, 1, 2, 2, 3, ...};
return table (x & 0xff] +
table ((x >> 8) & 0xff] +
table ((x >> 16) & 0xff] +
table ((x >> 24) & 0xff]);
}