代码之家  ›  专栏  ›  技术社区  ›  bangingmyheadontable

若在将掩码应用于变量时语句未执行,则应该

  •  0
  • bangingmyheadontable  · 技术社区  · 1 年前

    在我的例子中,我创建了一个名为testVar的整数变量,并使其等于十六进制中的a1。当打印出变量时,它表明它确实应该等于十六进制中的a1。现在,当在if语句中检查testVar是否等于a1时,if语句仅在变量没有应用掩码时执行。

    我的问题是“当变量应用了掩码时,为什么这些if语句不执行?”。

     #include <stdio.h>
    int testVar = 0xa1;   //testVar should equal 0x000000a1 now
    
    void main(){
        printf("%x \n",testVar);               //should prove that testVar is indeed equal to a1 in hex
        printf("%x \n",testVar & 0x000000ff);  //both printf functions are outputting a1
        
        
        if (testVar == 0x000000a1){      //this if statement works!
            printf("success1");      
        }
        if (testVar & 0x000000ff == 0x000000a1){      //this doesn't execute
            printf("success2");      
        }
        if (testVar & 0x000000ff == 0xa1){      //this doesn't execute
            printf("success3");      
        }
    }
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   dbush    1 年前

    相等运算符 == 具有比二进制逐位AND运算符更高的优先级 & 。这意味着:

    if (testVar & 0x000000ff == 0x000000a1)
    

    分析如下:

    if (testVar & (0x000000ff == 0x000000a1))
    

    这不是你想要的。使用括号确保正确分组:

    if ((testVar & 0x000000ff) == 0x000000a1)
    

    同样:

    if ((testVar & 0x000000ff) == 0xa1)