This question already has answers here: How to count the number of set bits in a 32-bit integer?                                                                    (53个答案)                                                                                        4年前关闭。                                如何仅使用> + |编写C程序&^〜! =那计算给定整数中的1的个数吗? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 看看斯坦福大学的Bit Twiddling hacks。这是您的问题的一些选择:天真的方法unsigned int v; // count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; v >>= 1){ c += v & 1;}带有查询表static const unsigned char BitsSetTable256[256] ={# define B2(n) n, n+1, n+1, n+2# define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)# define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) B6(0), B6(1), B6(1), B6(2)};unsigned int v; // count the number of bits set in 32-bit value vunsigned int c; // c is the total bits set in v// Option 1:c = BitsSetTable256[v & 0xff] + BitsSetTable256[(v >> 8) & 0xff] + BitsSetTable256[(v >> 16) & 0xff] + BitsSetTable256[v >> 24];// Option 2:unsigned char * p = (unsigned char *) &v;c = BitsSetTable256[p[0]] + BitsSetTable256[p[1]] + BitsSetTable256[p[2]] + BitsSetTable256[p[3]];// To initially generate the table algorithmically:BitsSetTable256[0] = 0;for (int i = 0; i < 256; i++){ BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];}布莱恩·W·克尼根(Brian W.unsigned int v; // count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; c++){ v &= v - 1; // clear the least significant bit set}还有更多算法,请阅读链接页面以获取详细信息。关于c - 仅使用<< >> + |计算给定整数中的位数&^〜! = ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29876592/ (adsbygoogle = window.adsbygoogle || []).push({});
10-10 01:23