在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
下面是使用divmod()函数的简单解决方案,该函数返回提示符和除法的结果,但不包含分数。
def dectobin(number):
bin = ''
while (number >= 1):
number, rem = divmod(number, 2)
bin = bin + str(rem)
return bin
其他回答
Python的字符串格式方法可以接受格式规范。
>>> "{0:b}".format(37)
'100101'
Python 2的格式规范文档
Python 3的格式规范文档
备选方案总结:
n=42
assert "-101010" == format(-n, 'b')
assert "-101010" == "{0:b}".format(-n)
assert "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
assert "0b101010" == bin(n)
assert "101010" == bin(n)[2:] # But this won't work for negative numbers.
贡献者包括John Fouhy, Tung Nguyen, mVChr, Martin Thoma。还有马丁·彼得斯。
如果你想要一个没有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)
下面是我刚刚实现的代码。这不是一个方法,但你可以把它作为一个现成的函数使用!
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
使用numpy pack/unpackbits,它们是你最好的朋友。
Examples
--------
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)