简体   繁体   中英

Counting number of 1 bits in C++ negative number

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.

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;
}

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.

// 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;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM