在Python中打印数字的位表示

76 投票
5 回答
115782 浏览
提问于 2025-04-15 12:32

我想把数字的二进制表示打印到控制台上,这样我就能看到所有对位进行的操作。

我该怎么在Python中做到这一点呢?

5 个回答

35

在 Python 2.6 及以上版本中:

print bin(123)

结果是:

0b1111011

在 Python 2.x 中

>>> binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
>>> binary(123)
[1, 1, 0, 1, 1, 1, 1]

注意,这个例子来自于: "Mark Dufour" 在 http://mail.python.org/pipermail/python-list/2003-December/240914.html

38

从 Python 2.6 开始 - 使用 string.format 方法

"{0:b}".format(0x1234)

特别是,你可能想要使用填充,这样打印不同的数字时,它们仍然能够对齐:

"{0:16b}".format(0x1234)

并且希望用前导的 0 来填充,而不是用空格:

"{0:016b}".format(0x1234)

从 Python 3.6 开始 - 使用 f-strings

用 f-strings 来写同样的三个例子,可以是:

f"{0x1234:b}"
f"{0x1234:16b}"
f"{0x1234:016b}"
95

这个意思吗?

>>> ord('a')
97
>>> hex(ord('a'))
'0x61'
>>> bin(ord('a'))
'0b1100001'

撰写回答