方法:i&(i-1)
如二进制1100 && 1011 =1000 相当于去掉最右边的1
//求一个整数中二进制1的个数 --普通方法
int Numof1(unsigned int i)
{
int count=0;
while(i)
{
if(i&1)
{
++count;
}
i>>=1;
}
return count;
}
int GetBitNumOfOne(int n) //http://zh.wikipedia.org/wiki/%E6%B1%89%E6%98%8E%E9%87%8D%E9%87%8F
{
n = ((0xaaaaaaaa & n) >> 1) + (0x55555555 & n);
n = ((0xcccccccc & n) >> 2) + (0x33333333 & n);
n = ((0xf0f0f0f0 & n) >> 4) + (0x0f0f0f0f & n);
n = ((0xff00ff00 & n) >> 8) + (0x00ff00ff & n);
n = ((0xffff0000 & n) >> 16) + (0x0000ffff & n);
return n;
}
//求一个整数中二进制1的个数
int Numof1_S(unsigned int i)
{
int count=0;
while(i)
{
++count;
i&=(i-1);
}
return count;
}
//判断一个正整数是不是2的正整数次幂
int isPowerBase2(unsigned int i)
{
return (i&(i-1))==0 ? 1 : 0;
}
#include
#include
int main(void) {
int N=10;
printf("%d\n",Numof1(N));
printf("%d\n",Numof1_S(N));
printf("%d\n",GetBitNumOfOne(N));
printf("%d\n",isPowerBase2(1024));
return 0;
}