Based on Robert's code here , this can be done even without division or module, replacing them with one shift and one AND, for example:
a = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4] x = 243 >> 4
Or in C:
const unsigned char oneBits[] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4}; unsigned char CountOnes(unsigned char x) { unsigned char results; results = oneBits[x&0x0f]; results += oneBits[x>>4]; return results }
For any size integer, you can just skip the bytes and do a quick search, for example:
def bits(n) a = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4] a[n >> 4] + a[n & 0x0f] end def setBits(n) total = 0 while(n > 0) total += bits(n&0xff) n >>= 8 end total end setBits(6432132132165432132132165436265465465653213213265465)
I am pleased with this answer. I knew something was more complicated and quadtree-esque would not be effective, I just thought it was a worthy thought experiment.