在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
公认的答案没有涉及负数,我将会讲到。 除了上面的答案,你也可以只使用bin和十六进制函数。在相反的方向上,使用二进制符号:
>>> bin(37)
'0b100101'
>>> 0b100101
37
但是对于负数,事情就变得有点复杂了。这个问题没有具体说明你想如何处理负数。
Python只是添加了一个负号,所以-37的结果是这样的:
>>> bin(-37)
'-0b100101'
在计算机/硬件二进制数据中,不存在负号。我们只有1和0。因此,如果您正在读取或生成由其他软件/硬件处理的二进制数据流,您首先需要知道正在使用的符号。
一种表示法是符号幅度表示法,其中第一位表示负号,其余为实际值。在这种情况下,-37将是0b1100101, 37将是0b0100101。这看起来像python生成的结果,但只是在正数/负数前面添加了0或1。
更常见的是Two的补码表示法,它看起来更复杂,结果与python的字符串格式有很大不同。您可以在链接中阅读详细信息,但是使用8位有符号整数-37将是0b11011011, 37将是0b00100101。
Python没有简单的方法来生成这些二进制表示。你可以使用numpy将Two的补码二进制值转换为python整数:
>>> import numpy as np
>>> np.int8(0b11011011)
-37
>>> np.uint8(0b11011011)
219
>>> np.uint8(0b00100101)
37
>>> np.int8(0b00100101)
37
但我不知道一个简单的方法来做相反的内置函数。位串包可以提供帮助。
>>> from bitstring import BitArray
>>> arr = BitArray(int=-37, length=8)
>>> arr.uint
219
>>> arr.int
-37
>>> arr.bin
'11011011'
>>> BitArray(bin='11011011').int
-37
>>> BitArray(bin='11011011').uint
219
其他回答
如果你正在寻找与hex()等价的bin(),它是在python 2.6中添加的。
例子:
>>> bin(10)
'0b1010'
备选方案总结:
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。还有马丁·彼得斯。
这是我的答案,它工作得很好…!
def binary(value) :
binary_value = ''
while value !=1 :
binary_value += str(value%2)
value = value//2
return '1'+binary_value[::-1]
如果你想要一个没有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 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