开发者

Why does this function not work for negative numbers?

I an using the following function to calculat开发者_JS百科e the set bits in an integer, and it works for positive numbers, but not for negative numbers. Can anyone explain why?

int CountSetBits(int number)
{
    int count = 0;
    while (number > 0)
    {
        count += (number & 0x01);
        number >>= 1;
    }

    return count;
}


    while (number > 0)

Will immediately end (since number < 0 from the onset)

You can force it to treat the number as unsigned:

    unsigned int new_number = number;

And then it should work with new_number (this works because of how the sign bit is implemented)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜