ake*_*ent 69
这种事情?
>>> ord('a')
97
>>> hex(ord('a'))
'0x61'
>>> bin(ord('a'))
'0b1100001'
Run Code Online (Sandbox Code Playgroud)
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)