在python中打印数字的位表示

viv*_*mar 54 python

我想在控制台上打印数字的位表示,以便我可以看到所有正在对位进行的操作.

我怎么能在python中做到这一点?

ake*_*ent 69

这种事情?

>>> ord('a')
97
>>> hex(ord('a'))
'0x61'
>>> bin(ord('a'))
'0b1100001'
Run Code Online (Sandbox Code Playgroud)

  • 严格来说,这是数字的二进制表示,但不一定是内存中的底层位. (2认同)

gah*_*ooa 29

在Python 2.6+中:

print bin(123)
Run Code Online (Sandbox Code Playgroud)

结果是:

0b1111011
Run Code Online (Sandbox Code Playgroud)

在python 2.x中

>>> binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
>>> binary(123)
[1, 1, 0, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)

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


Fin*_*ter 26

从Python 2.6 - 使用string.format方法:

"{0:b}".format(0x1234)
Run Code Online (Sandbox Code Playgroud)

特别是,您可能希望使用填充,以便不同数字的多个打印仍然排列:

"{0:16b}".format(0x1234)
Run Code Online (Sandbox Code Playgroud)

并且使用前导0而不是空格留下填充:

"{0:016b}".format(0x1234)
Run Code Online (Sandbox Code Playgroud)

从Python 3.6 - 使用f-strings:

使用f字符串的相同三个示例将是:

f"{0x1234:b}"
f"{0x1234:16b}"
f"{0x1234:016b}"
Run Code Online (Sandbox Code Playgroud)