简体   繁体   English

python按位运算的奇怪结果

[英]Weird outcome of python bitwise operation

Anyone could explain?谁能解释一下? I get really confused by the following outcome.我对以下结果感到非常困惑。 Thanks a lot!非常感谢!

why this doesn't work!???为什么这不起作用!???

`i = 2
table[i] = i&1 + table[i>>1] `

the following works以下作品

`tmp = i&1
 table[i] = tmp + table[i>>1]`

This is because of parens gruopings and & having less precedence: Here's an example of how this works:这是因为 parens groopings 和 & 的优先级较低:这是一个如何工作的例子:

2& will not happen until 2+ 2 >> 2
In [569]: 2&2 + 2>>2                                                                                                                                                                           
Out[569]: 0

Here we use the and in parens first, before adding to 2>>2
In [570]: (2&2) + 2>>2                                                                                                                                                                         
Out[570]: 1

Here's what the operator precedence looks like for the original operation:
In [571]: 2&(2 + 2>>2)                                                                                                                                                                         
Out[571]: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM