Logical vs. bitwise operator AND

给你一囗甜甜゛ 提交于 2020-01-24 09:40:10

问题


I don’t understand the difference between & and and, even if I read some other questions about it.

My code is:

f=1
x=1

f==1 & x==1
Out[60]: True

f==1 and x==1
Out[61]: True

f=1
x=2

f==1 and x==2
Out[64]: True

f==1 & x==2
Out[65]: False

Why is it the second & False, whereas the first is True?


回答1:


The issue is that & has higher operator precedence than ==.

>>> (f == 1) & (x == 2)
True
>>> f == (1 & x) == 2
False

Perhaps this seems unintuitive, but & is really meant to be used between numbers for particular kinds of calculations:

>>> 3 & 5
1

so it has similar precedence to operators like + and *, which sensibly should be evaluated before ==. It's not meant to be used in a similar manner to and at all.




回答2:


The problem is that '&' has higher priority than ==. If you put your last statement like:

(f==1) & (x==2)

You will get your desired result.




回答3:


In the second case, your code is:

f == (1 & x) == 2

1 & 2 is 0:

00000001
00000010 &
--------
00000000

So your final statement looks:

1 == 0 == 2

Which is False.



来源:https://stackoverflow.com/questions/36310789/logical-vs-bitwise-operator-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!