在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
Python 3.6增加了一种新的字符串格式化方法,称为格式化字符串字面量或“f-strings”。 例子:
name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"
输出将是“你好,Bob,您的号码是00001010!”
关于这个问题的讨论可以在这里找到-在这里
其他回答
由于前面的答案大多使用format(), 这是一个f字符串的实现。
integer = 7
bit_count = 5
print(f'{integer:0{bit_count}b}')
输出:
00111
为了方便起见,这里有python文档中格式化字符串文字的链接:https://docs.python.org/3/reference/lexical_analysis.html#f-strings。
这是针对python3的,它保持前导0 !
print(format(0, '08b'))
n=input()
print(bin(n).replace("0b", ""))
有点类似的解决方案
def to_bin(dec):
flag = True
bin_str = ''
while flag:
remainder = dec % 2
quotient = dec / 2
if quotient == 0:
flag = False
bin_str += str(remainder)
dec = quotient
bin_str = bin_str[::-1] # reverse the string
return bin_str
这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况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']