作者cplusplus (C++)
看板C_and_CPP
标题Re: [问题] 数1个byte中有几个bit为1
时间Sat Feb 18 23:15:11 2006
节省一下用个大小16的表就好了...
int CountBits(unsigned char i)
{
static int table[]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
return table[i&0xf]+table[i>>4];
}
之前有一个怀念的演算法 曾经在离散课上提到
count=0;
while(a!=0)
{
count++;
a=a&(a-1);
}
任何二进位表示都是0跟1的组合
每次减1时就会早成该最右边的1变成0且其右边的bit接变为 1
例如
192 =11000000
192-1=191=10111111 经过 &(AND)
=10000000
一直做到原来的值变成0就可以知道有几个1了...
有趣 不过最快的还是查表...:P
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.115.217.14
1F:推 cutecpu:推,好强的离散演算法 02/19 00:05