Count bits in the number [duplicate]

时光毁灭记忆、已成空白 提交于 2019-11-29 05:23:16

There is a bit counting algorithm without a loop at http://graphics.stanford.edu/~seander/bithacks.html. Lots of bit counting algorithms at http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/

Well, of course there is, but you're not going to like it.

You could, of course, build a lookup table with all the correct values in it:

table[1] = 1, table[2] = 1, table[3] = 2, etc.

So, this would give you a really fast answer, but it's a completely useless solution by itself, since the table would have to be very, very large.

You could optimize this a bit, but it requires just a little iteration. Simply create an 8-bit version of the table solution, a mere 256-entry table, then iterate over each BYTE in the value to be checked, summing the results of the table lookup. Something like:

short int tableLookup[256] = { 0, 1, 1, 2, 1, ... };
unsigned int valueToCheck = 89392491;
int result = 0;
while ( valueToCheck != 0 ) {
   result += tableLookup[ (valueToCheck & 0xFF) ];
   valueToCheck >>= 8;
}
// result should now have the correct bit count, if the table is correct.

Hmm, seems this is well known (and here I was doing this off the top of my head): http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

Yes, you can do that by using a look up table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!