Rajesh kumar
Rajesh kumar

Reputation: 11

Coding : Can anyone explain me this why there are different outputs when comparing Least significant bits of two numbers?

Can anyone explain me this why there are different outputs when comparing Least significant bits of two numbers?
In 1st case I comparing them directly
In second case I assigned LSB to other variables

        //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"); 


            }

Output :

Least significant bits are for M : 1 and for P : 1
Least significant bits are not equal
Value in MLSB : 1 and Value in PLSB : 1
Least significant bits are equal

Upvotes: 0

Views: 57

Answers (2)

thomachan
thomachan

Reputation: 398

please check operator precedence.

if(M&1 != P&1)

this will comapare (1 != P), which returns true. add brackets around bitwise operation.

Upvotes: 2

4386427
4386427

Reputation: 44329

Try changing this

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

into

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

and then check the precedence of operators, e.g. here https://en.cppreference.com/w/c/language/operator_precedence

Upvotes: 2

Related Questions