在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
一个简单的方法是使用字符串格式,请参阅本页。
>> "{0:b}".format(10)
'1010'
如果你想要一个固定长度的二进制字符串,你可以使用这个:
>> "{0:{fill}8b}".format(10, fill='0')
'00001010'
如果需要使用two的补码,那么可以使用下面的行:
'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)
其中n是二进制字符串的宽度。
其他回答
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 inttobinary(number):
if number == 0:
return str(0)
result =""
while (number != 0):
remainder = number%2
number = number/2
result += str(remainder)
return result[::-1] # to invert the string
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
输出:
1010
这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况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的字符串格式方法可以接受格式规范。
>>> "{0:b}".format(37)
'100101'
Python 2的格式规范文档
Python 3的格式规范文档