编码:谁能解释我为什么比较两个数字的最低有效位时会有不同的输出?

时间:2018-08-10 05:54:59

标签: c bitwise-operators

有人能解释一下为什么比较两个数字的最低有效位时会有不同的输出吗?
在第一种情况下,我直接比较它们
在第二种情况下,我将LSB分配给其他变量

        //Program to check Least significant bits of two numbers 
        #include<stdio.h>
            int main(){

                //LSB means least significant bit of the binary number
                //(i.e.,Unit place digit in binary number) 
                //Example..... 2 = 10(in binary) and 9 = 1001(in binary)  
                //so least significant bit is 0 for 2 and 1 for 9

               //In binary M =101 and LSB of M = 1 
               int M = 5; 
               //In binary P = 011 and LSB of P  = 1
               int P = 3;

               //printing LSB values
               printf("\nLeast significant bits are for M : %d and for P : %d",M&1,P&1);

               //Comparing LSB of M and LSB of P
               if(M&1 != P&1) { 
                   printf("\nLeast significant bits are not equal"); 
               }
               else printf("\nLeast significant bits are equal"); 

               //Assigning Least significant bit of M to MLSB
               int MLSB = M&1; 
               //Assigning Least significant bit of P to PLSB
               int PLSB = P&1; 

               //printing LSB values
               printf("\nValue in MLSB : %d and Value in PLSB : %d",MLSB,PLSB); 

               //Comparing MLSB and PLSB
               if(MLSB != PLSB) { 
                   printf("\nLeast significant bits are not equal"); 
               }
               else printf("\nLeast significant bits are equal"); 


            }

输出:

最低有效位适用于M:1和P:1
最低有效位不相等
MLSB中的值:1和PLSB中的值:1
最低有效位相等

2 个答案:

答案 0 :(得分:2)

尝试更改此内容

if(M&1 != P&1) {

进入

if((M&1) != (P&1)) {

,然后检查运算符的优先级,例如这里https://en.cppreference.com/w/c/language/operator_precedence

答案 1 :(得分:2)

请检查operator precedence

if(M&1 != P&1)

这将是comapare(1!= P),返回true。在按位操作周围添加括号。