Python中的>>运算符

36 投票
5 回答
51160 浏览
提问于 2025-04-16 02:21

>> 这个符号叫做“右移运算符”。它的作用是把一个数字的二进制表示向右移动指定的位数。简单来说,就是把数字的“位”往右边挪动。比如说,10 >> 1 这个操作,就是把数字10的二进制形式向右移动1位。这样一来,原本的数字就变成了5。

5 个回答

6

你其实可以自己重载右移操作符(>>)。

>>> class wierd(str): 
... def __rshift__(self,other): 
... print self, 'followed by', other 
... 
>>> foo = wierd('foo') 
>>> bar = wierd('bar') 
>>> foo>>bar 
foo followed by bar 

参考链接:http://www.gossamer-threads.com/lists/python/python/122384

23

>><<右移左移的位运算符,也就是说,它们会改变数字的二进制表示(虽然也可以用在其他数据结构上,但Python并没有实现这一点)。这些运算符在一个类中是通过 __rshift__(self, shift)__lshift__(self, shift) 来定义的。

例子:

>>> bin(10) # 10 in binary
1010
>>> 10 >> 1 # Shifting all the bits to the right and discarding the rightmost one
5 
>>> bin(_) # 5 in binary - you can see the transformation clearly now
0101 

>>> 10 >> 2 # Shifting all the bits right by two and discarding the two-rightmost ones
2
>>> bin(_)
0010

快捷方式: 你可以通过将一个数字右移指定的位数,来实现整数除法(也就是去掉余数,在Python中可以用 // 来实现),这个位数是你右移的位数对应的2的幂。

>>> def rshift(no, shift = 1):
...     return no // 2**shift
...     # This func will now be equivalent to >> operator.
...
56

这是右移位运算符,它会把所有的位向右移动一次。

数字10用二进制表示是

1010

向右移动后变成

0101

这就是数字5。

撰写回答