Hi,(adsbygoogle = window.adsbygoogle || []).push({});

For example, say we have the binary integer 101010 and I split it into blocks, say (1)(01)(01)(0). The size of the blocks is determined by some function. We want to count the number of '1' bits inside each of these blocks.

I'm interested in a fast C++ code to do this. There are fast codes out there to compute the number of '1' bits in arbitrary integers, and it would be great if the solution to this problem could be obtained by a modification of those codes (which I do not understand), so that it is as fast as it can be. For instance, here's one of those "ugly" fast codes (the one I'm using in my project) which I found in another forum:

int bitcount(int i) {

i = i - ( (i >> 1) & 0x55555555);

i = (i & 0x33333333) + ( (i >> 2) & 0x33333333 );

return (((i + (i >> 4)) & 0x0F0F0F0F) * 0X01010101) >> 24;

}

Many thanks for the help.

**Physics Forums | Science Articles, Homework Help, Discussion**

Join Physics Forums Today!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# [C++] Efficiently counting the number of '1' bits inside blocks of a binary number

**Physics Forums | Science Articles, Homework Help, Discussion**