为什么这个按位运算的 if 语句的变化会导致错误?

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

我正在编写一个函数来打印位,但我 运行 遇到了问题。这两个 for 循环对我来说似乎是相同的,但出于某种原因,被注释掉的循环没有打印出正确的位。

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){


   for (int i = 1; i <= numbOfBits; i++){
       if ((mask & bit) == 0 ){
            cout << "0";
       }
       else {

       cout <<"1";
       }
       mask = mask >> 1;
       if ( i %4 == 0 ){
        cout << " ";
       }
   }

/*   for(int i= 1 ; i <= numbOfBits ; i++ ){
         if ((mask & bit) ==1){
            cout << "1";
         }
         else{
            cout << "0";

         }
      mask = mask >> 1;
      if(i% 4 ==0){
         cout << " ";
      }
   }*/
}

原因很简单:掩码值可能从 128 开始,然后右移到 64、32 等。所以,在...

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

...如果设置了屏蔽位,则按位 AND 将 return 屏蔽位,一切都按预期进行。但是在...

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

按位与 returns 可能大于 1 的掩码位:例如 128 != 1,即使您正在测试的位已设置,您也会错误地认为它已关闭。只有当 mask 最终右移到 1.

时它才会起作用