在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
我很惊讶,没有提到一个很好的方法来实现这一点,使用Python 3.6及更高版本支持的格式化字符串。TLDR:
>>> number = 1
>>> f'0b{number:08b}'
'0b00000001'
长故事
这是Python 3.6提供的格式化字符串的功能:
>>> x, y, z = 1, 2, 3
>>> f'{x} {y} {2*z}'
'1 2 6'
你也可以请求二进制文件:
>>> f'{z:b}'
'11'
指定宽度:
>>> f'{z:8b}'
' 11'
请求零填充:
f'{z:08b}'
'00000011'
并添加公共前缀表示二进制数:
>>> f'0b{z:08b}'
'0b00000011'
你也可以让Python为你添加前缀,但我不喜欢上面的版本,因为你必须把前缀考虑到宽度:
>>> f'{z:#010b}'
'0b00000011'
更多信息可在格式化字符串文字和格式规范迷你语言的官方文档中获得。
其他回答
我觉得Martijn Pieter的评论值得强调作为答案:
binary_string = format(value, '0{}b'.format(width))
对我来说,它既清晰又万能。
这是我的答案,它工作得很好…!
def binary(value) :
binary_value = ''
while value !=1 :
binary_value += str(value%2)
value = value//2
return '1'+binary_value[::-1]
这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况0不返回任何内容)。
def toBin(num):
if num == 0:
return ""
return toBin(num//2) + str(num%2)
print ([(toBin(i)) for i in range(10)])
['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
Python 3.6增加了一种新的字符串格式化方法,称为格式化字符串字面量或“f-strings”。 例子:
name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"
输出将是“你好,Bob,您的号码是00001010!”
关于这个问题的讨论可以在这里找到-在这里
如果你想要一个没有0b前缀的文本表示,你可以使用这个:
get_bin = lambda x: format(x, 'b')
print(get_bin(3))
>>> '11'
print(get_bin(-3))
>>> '-11'
当你想要n位表示时:
get_bin = lambda x, n: format(x, 'b').zfill(n)
>>> get_bin(12, 32)
'00000000000000000000000000001100'
>>> get_bin(-12, 32)
'-00000000000000000000000000001100'
或者,如果你喜欢有一个函数:
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str
"""
return format(x, 'b').zfill(n)