您好,我正在编写一个十进制到二进制的函数,我发现这段代码可以完美运行:
while n > 0:
b = str(n % 2) + b
n >>= 1
但是我不知道 >>=
的作用,你能启发我吗?
非常感谢
最佳答案
这是一个二进制右移运算。 n
中的位向右移动 1。这相当于 n = n >> 1
。
来自BitwiseOperators in python :
x >> y
: Returnsx
with the bits shifted to the right byy
places. This is the same as//
'ingx
by2**y
.
例如,假设一个整数 4
,我们将其向右移动 1
位。
# First let's look at what 4 is in binary.
>>> bin(4)[2:].zfill(8) # this pads to 8 bits.
'00000100'
# If you shift all the bits towards the right 1 places the result is
# '00000010', which in turn is 2 in base 10.
>>> 4 >> 1
2
>>> bin(2)[2:].zfill(8)
'00000010'
关于Python >>= 十进制转二进制函数的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22089492/