c++ - why does a variation in the if statement of this bitwise operation cause an error? -


i writing function print bits ran problem. 2 loops seem identical me reason 1 commented out not print right bits.

int main() { unsigned int bits = 0x570fa1;  unsigned int mask = 0x800000;  printbits(bits, 24, mask);    return 0; } void printbits(unsigned int bit, int numbofbits, unsigned int& mask){      (int = 1; <= numbofbits; i++){        if ((mask & bit) == 0 ){             cout << "0";        }        else {         cout <<"1";        }        mask = mask >> 1;        if ( %4 == 0 ){         cout << " ";        }    }  /*   for(int i= 1 ; <= numbofbits ; i++ ){          if ((mask & bit) ==1){             cout << "1";          }          else{             cout << "0";           }       mask = mask >> 1;       if(i% 4 ==0){          cout << " ";       }    }*/ } 

reason's simple: mask value might start @ 128, right-shifted 64, 32, etc.. so, in...

if ((mask & bit) == 0 ){ 

...if masked bit set bitwise , return mask bit, , works hoped. in...

if ((mask & bit) ==1){ 

the bitwise , returns mask bit may greater 1: example 128 != 1, , though bit you're testing set mistakenly think it's off. time happen work when mask has been right-shifted 1.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -