在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?

谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。


当前回答

使用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 binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

输出:

1010

如果你愿意放弃“纯”Python,但获得大量火力,这里有Sage -示例:

sage: a = 15
sage: a.binary()
'1111'

您将注意到它以字符串形式返回,因此要将它用作数字,您需要执行如下操作

sage: eval('0b'+b)
15
n=input()
print(bin(n).replace("0b", ""))
try:
    while True:
        p = ""
        a = input()
        while a != 0:
            l = a % 2
            b = a - l
            a = b / 2
            p = str(l) + p
        print(p)
except:
    print ("write 1 number")

我觉得Martijn Pieter的评论值得强调作为答案:

binary_string = format(value, '0{}b'.format(width))

对我来说,它既清晰又万能。