我在看的设置位计数问题(给出一个二进制数,如何有效地计算有多少位设置)解决方案。
在这里, http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive ,我已经找到了一些方法。
怎么样的查表法? 我不明白的二进制表示法/数的特性,使其工作。
static const unsigned char BitsSetTable256[256] =
{
# define B2(n) n, n+1, n+1, n+2
# define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
# define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
B6(0), B6(1), B6(1), B6(2)
};
unsigned int v; // count the number of bits set in 32-bit value v
unsigned int c; // c is the total bits set in v
// Option 1:
c = BitsSetTable256[v & 0xff] +
BitsSetTable256[(v >> 8) & 0xff] +
BitsSetTable256[(v >> 16) & 0xff] +
BitsSetTable256[v >> 24];
// Option 2:
unsigned char * p = (unsigned char *) &v;
c = BitsSetTable256[p[0]] +
BitsSetTable256[p[1]] +
BitsSetTable256[p[2]] +
BitsSetTable256[p[3]];
// To initially generate the table algorithmically:
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
特别是,我不明白BitsSetTable256
定义在第一。 为什么定义这些量B2,B4,...? 在我看来,他们不是事后使用。
你可以暗示的二进制表示进一步的文档?
谢谢!