What is the difference between if (x ^ 1! = 1) and if (int (x ^ 1)! = 1) in C ++?

I am trying to find if x first bit on the right is 1 , so I am checking if the value is x^1 1 . but

 int x=6; if (x^1!=1) 

gives the wrong answer but

 if (int(x^1)!=1) 

gives the correct answer.

I do not know why. Can anyone clarify this for me?

+8
c ++ bitwise-operators
source share
3 answers

This is a trap operator priority . Operator priority determines how operations are “grouped” (for example, how 2*3+4 results in a 2*3 grouping). Adding brackets changes how things are “grouped” (for example, 2*(3+4) leads to grouping 3+4 ).

x^1!=1 equivalent to x^(1!=1) , which can be simplified to x^0 .

int(x^1)!=1 equivalent to (x^1)!=1 (since you manually added parentheses here, the int part is not very important, these are important brackets).

As you can see, x^(1!=1) and (x^1)!=1 do not match.

If your goal is to check the first bit, I would suggest using bit-AND ( & ). Then you can just do if (x & 1) (but be careful, mixing & == will lead to the same problems as before, so use parentheses if you want to write if ((x & 1) == 1) ).

+13
source share

Simple,! = (Uneven Relational Operator) takes precedence over ^ (bitwise XOR operator). Check priority

 int x=6; 

case 1: if (x^1!=1)

First 1!=1 is 0 ; then 6^0= 6 . ( 110 ^ 000 = 110 ); Check XOR table

Case 2: if (int (x^1)!=1)

First x^1= 7 ; then 7!=1 is 1 (true).

0
source share

@Cornstalks is right with his answer.

I just had this in mind (it really does not answer your problem, but can make it more readable):

Another approach to solving this problem is to simply use the modulo operator:

 if(x%2 == 0) // then first bit is 0 else // first bit is 1 

Ultimately, your task is simply to check the even or odd values.

0
source share

All Articles