您的位置:首页 > 其它

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

2016-08-30 14:02 459 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐