在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
输出:
1010
其他回答
numpy。binary_repr(全国矿工工会,width = band)
例子来自上面的文档链接:
> > > np.binary_repr (3) “11” > > > np.binary_repr (3) “-11” > > > np。binary_repr(宽度= 4) “0011” 当输入数字为负数并且指定width时,返回2的补数: > > > np。binary_repr(3、宽度= 3) “101” > > > np。binary_repr(宽度= 5) “11101”
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
输出:
1010
Python 3.6增加了一种新的字符串格式化方法,称为格式化字符串字面量或“f-strings”。 例子:
name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"
输出将是“你好,Bob,您的号码是00001010!”
关于这个问题的讨论可以在这里找到-在这里
如果你正在寻找与hex()等价的bin(),它是在python 2.6中添加的。
例子:
>>> bin(10)
'0b1010'
我觉得Martijn Pieter的评论值得强调作为答案:
binary_string = format(value, '0{}b'.format(width))
对我来说,它既清晰又万能。