简洁判断一个byte中有多少位为1的bit?

以下是Brian W. Kernighan公开的一个方法

unsigned bit_count(unsigned v)
{
    unsigned int c; //置位总数累计
    
    for (c = 0; v; c++)
    {
        v &= v - 1; //去掉最低的置位
    }
    
    return c;
}

// 15的二进制为1111, 调用后为1的bit数为 4
unsigned bitNum = bit_count(15);

以上方法在VC6.0 + Win7下通过验证。
原文地址:https://www.cnblogs.com/tyjsjl/p/3240752.html