在Python中l =(2 <&lt; 2 | 3&lt;&lt; 2)的含义

时间:2014-10-14 15:13:21

标签: python

我不确定上面的表达式在Python中意味着什么。有些谷歌搜索但仍然没有。 l的值是12。

感谢您的帮助。

2 个答案:

答案 0 :(得分:8)

他们是按位操作。 (Binary bitwise operationsShifting operations

如果用二进制表示数字,就会更容易理解。

>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> bin(2 << 2)  # << : Shift left
'0b1000'
>>> bin(3 << 2)
'0b1100'
>>> bin(2 << 2 | 3 << 2)
'0b1100'

>>> int('1100', 2)
12

答案 1 :(得分:1)

这只是位移运算符和二进制OR,意思是

2 << 2 # shift 2 which is 0b00010 left by two positions

3 << 2 # shift 3 which is 0b00011 left by two positions

(2 << 2 | 3 << 2) take OR of these values