function to count the number of "1" of one byte

来源:互联网 发布:u盘插在mac上没反应 编辑:程序博客网 时间:2024/06/05 08:36

function to count the number of "1" of one byte ,for example 5(0101)has two "1"

经常遇到的面试题,毫无疑问需要借助位操作:


unsigned int bitCount (unsigned int value) {    unsigned int count = 0;    while (value > 0) {           // until all bits are zero        //if ((value & 1) == 1)     // check lower bit        //    count++;count += value & 0x1;        value >>= 1;              // shift bits, removing lower bit//printf("value:%d, count:%d\n", value, count);    }    return count;}


0 0