计算二进制位有多少位1
最近着迷于位运算,有这样一个问题如何算出一个数的二进制有多位1呢?
比较好的有下面两种方法
第一种:
unsigned int countBit(unsigned int n){unsigned int count = 0;while(n){count++;n&=n-1;}return count;}unsigned int countBit2(unsigned int nValue){nValue = ((0xaaaaaaaa & nValue)>>1) + (0x55555555 & nValue);nValue = ((0xcccccccc & nValue)>>2) + (0x33333333 & nValue);nValue = ((0xf0f0f0f0 & nValue)>>4) + (0x0f0f0f0f & nValue);nValue = ((0xff00ff00 & nValue)>>8) + (0x00ff00ff & nValue);nValue = ((0xffff0000 & nValue)>>16) + (0x0000ffff & nValue);return nValue;}