Can someone explain how this works?
#define BX_(x) ((x) - (((x)>>1)&0x77777777) \
- (((x)>>2)&0x33333333) \
- (((x)>>3)&0x11111111))
#define BITCOUNT(x) (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
Clarification:
Ideally, the answer will start something along the lines of:
The macro: “BX_” subtracts three values from the passed in number.
These three values represent:
- XXXXX
- YYYYY
- ZZZZZ
This allows the BITCOUNT() to work as follows…
Cheers,
David
The output of BX_(x) is the number of on bits in each hex digit. So
The following:
shuffles the counts into bytes:
Taking this result modulo 255 adds up the individual bytes to arrive at the correct answer 14. To see that this works, consider just a two-byte integer, 256*X + Y. This is just 255*X + X + Y, and 255*X % 255 is always zero, so
This extends to four-byte integers:
256^3*V + 256^2*W + 256*X + Y
Just replace each 256 with (255+1) to see that
The final observation (which I swept under the rug with the 2-digit example) is that
V + W + X + Yis always less than 255, so