In C++, I would like to compute the number of bits that is 1 in a uint64_t
# A few examples in uint8_t:
0b00000000 ==> 0
0b01000001 ==> 2
0b00110101 ==> 4
0b11111111 ==> 8
I need to perform a lot (say millions) of such operations, is there a fast way to do so (maybe with some pre-processing)?
One possibility I can think of is to create a lookup table for every N
bit (say N=8
), and perform 64/N
lookups for a uint64_t
. Is there a better solution for this? If I decide to go for the above approach, how should I set N
? (To my understanding even ignoring all pre-processing computation, it is not the case that the larger N
is, the better, Because the look-up speed actually depends on whether the look-up table can fit in cache?)
Thanks a lot!