在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 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)

有点类似的解决方案

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 

Python 3.6增加了一种新的字符串格式化方法,称为格式化字符串字面量或“f-strings”。 例子:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

输出将是“你好,Bob,您的号码是00001010!”

关于这个问题的讨论可以在这里找到-在这里

这是我的答案,它工作得很好…!

def binary(value) :
    binary_value = ''
    while value !=1  :
        binary_value += str(value%2)
        value = value//2
    return '1'+binary_value[::-1]

计算二进制数:

print("Binary is {0:>08b}".format(16))

计算一个数的十六进制小数:

print("Hexa Decimal is {0:>0x}".format(15))

计算所有的二进制直到16::

for i in range(17):
   print("{0:>2}: binary is {0:>08b}".format(i))

要计算十六进制小数,直到17

 for i in range(17):
    print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
##as 2 digit is enogh for hexa decimal representation of a number