rdasxy
rdasxy

Reputation: 1661

Why does this function not work for negative numbers?

I an using the following function to calculate 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;
}

Upvotes: 0

Views: 407

Answers (1)

Foo Bah
Foo Bah

Reputation: 26251

    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)

Upvotes: 6

Related Questions