>>做什么和<<在Python中意味着什么?
问题描述:
我注意到我可以做类似2 << 5
来获得64和1000 >> 2
来获得250的事情.
I notice that I can do things like 2 << 5
to get 64 and 1000 >> 2
to get 250.
我也可以在print
中使用>>
:
print >>obj, "Hello world"
这是怎么回事?
答
这些是按位移位运算符.
These are bitwise shift operators.
引用文档:
x << y
返回x
,其位向左偏移y个位(右侧的新位为零).这与x
乘2**y
相同.
Returns x
with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x
by 2**y
.
x >> y
返回x
,其位向右移y个位.这与将x
除以2**y
相同.
Returns x
with the bits shifted to the right by y places. This is the same as dividing x
by 2**y
.