求bit中1的个数有几种做法
求bit中1的个数有几种做法:
- x & (x - 1)
- Hamming weight的经典求法,基于树状累加:http://en.wikipedia.org/wiki/Hamming_weight
- 内存足够大可以查表得;
int
bitCount(unsigned
int
u)
{
unsigned
int
uCount;
uCount
= u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return
((uCount
+ (uCount >> 3)) & 030707070707) % 63;
}