Counting number of 1 bits in C++ negative number

2.9k Views Asked by At

The following function:

int numOnesInBinary(int number) {
    int numOnes = 0;
    while (number != 0) {
        if ((number & 1) == 1) {
            numOnes++;
        }
        number >>= 1;
    }
    return numOnes;
}

will only work for positive numbers, because in the case of a negative number, it always add a 1 to the leftmost bit when doing the >> operation. In Java we can use >>> instead, but how can we do it in C++? I read in a book that we can use unsigned integers in C++, but I don't see how since unsigned integers cannot represent negative numbers.

4

There are 4 best solutions below

5
nh_ On

Cast number to unsigned int and perform your counting on that:

int numOnesInBinary(int number) {
    int numOnes = 0;
    unsigned int unumber = static_cast<unsigned int>(number);
    while (unumber != 0) {
        if ((unumber & 1) == 1) {
            numOnes++;
        }
        unumber >>= 1;
    }
    return numOnes;
}
0
Mark Shevchenko On

Unsigned integer lets to count bits in a simple loop.

Casting from signed to unsigned makes invalid result, if we speak about the values:

char c = -127;
unsigned char u = (unsigned char)c; // 129

But if we speak only about the form, it's not changed:

1 0 0 0 0 0 0 1 == decimal signed -127
1 0 0 0 0 0 0 1 == decimal unsigned 129

So casting to unsigned is just a hack.

1
balabhi On
// How about this method, as hinted in "C Book" by K & R.
// Of course better methods are found in MIT hackmem   
// http://www.inwap.com/pdp10/hbaker/hakmem/hakmem.html  
//
int numOnesInBinary(int number) {
    int numOnes = 0;
    // Loop around and repeatedly clear the LSB by number &= (number -1).  
    for (; number; numOnes++, number &= (number -1));
    return numOnes;
}
3
arpit1714 On

count represents the number of set bits in the integer n if size of integer is 32 bits then

int count =0;  

int n = -25 //(given)
for(int k=0;k<32;k++){
     if ((n >> k) & 1){
        count++;
     }
}

return  count;