Python >>= 十进制转二进制函数的帮助

标签 python

您好,我正在编写一个十进制到二进制的函数,我发现这段代码可以完美运行:

while n > 0:
    b = str(n % 2) + b
    n >>= 1

但是我不知道 >>= 的作用,你能启发我吗?

非常感谢

最佳答案

这是一个二进制右移运算。 n 中的位向右移动 1。这相当于 n = n >> 1

来自BitwiseOperators in python :

x >> y: Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**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/

相关文章:

python - 如何实时绘制中断线

python - 为什么我的 Project Euler #12 代码这么慢?

python - 如何使用 QTableView 创建列标题及其标签

python - 如何使用正则表达式遍历字符?

python - 具有多个 for 子句的列表理解的 Map/reduce 等价物

python - 须藤 : python: command not found

python - 在 Python 中创建一个 "actual"for 循环?

python - 在 Django 模板中从 JSON 中转义 html 实体

python - 在 wxPython 中使用线程将面板添加到 GUI

python - 子类化 sklearn LinearSVC 以用作 sklearn GridSearchCV 的估计器