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?
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)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With