Reputation:
I am trying to find if x
's first bit from right is 1
, so I check if the value of x^1
is 1
. However,
int x=6;
if (x^1!=1)
gives wrong answer, but
if (int(x^1)!=1)
gives the correct answer.
I am not sure why. Could someone clarify this for me?
Upvotes: 8
Views: 226
Reputation: 6740
@Cornstalks is right with his answer.
I just had that in mind ( it does'nt in fact answer your problem , but can make it more readable) :
Another approach for solving this problem is simply using the modulo operator:
if(x%2 == 0) // then first bit is 0
else // first bit is 1
In the end your task is simply a check for even or odd values.
Upvotes: 0
Reputation: 517
Simply, != (Not equal relational operator) has high precedence than ^ (XOR bitwise operator). Check precedence
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).
Upvotes: 0
Reputation: 38228
It's a trap of operator precedence. Operator precedence determines how operations are "grouped" (like how 2*3+4
results in the 2*3
being "grouped" together). Adding parentheses changes how things are "grouped" (for example, 2*(3+4)
causes 3+4
to be "grouped" together).
x^1!=1
is equivalent to x^(1!=1)
, which can be simplified to x^0
.
int(x^1)!=1
is equivalent to (x^1)!=1
(because you've manually added parentheses here; the int
part isn't very relevant; it's the parentheses that are important).
As you can see, x^(1!=1)
and (x^1)!=1
are not the same.
If your goal is to check the first bit, I might suggest using a bitwise-AND (&
). You can then just do if (x & 1)
(but beware, mixing &
and ==
will result in the same issues as you were having before, so use parentheses if you want to write if ((x & 1) == 1)
).
Upvotes: 13