【问题标题】:Weird outcome of python bitwise operationpython按位运算的奇怪结果
【发布时间】:2019-12-13 02:52:59
【问题描述】:

谁能解释一下?我对以下结果感到非常困惑。非常感谢!

为什么这不起作用!???

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

以下作品

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

【问题讨论】:

  • 使用括号。 table[i] = (i & 1) + table[i >> 1] 有效

标签: python bit-manipulation


【解决方案1】:

这是因为括号分组和 & 具有较少的优先级:这是一个如何工作的示例:

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

【讨论】:

    猜你喜欢
    • 2023-01-16
    • 1970-01-01
    • 2012-07-23
    • 2012-10-24
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 2016-01-22
    • 2016-07-26
    相关资源
    最近更新 更多