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

其他回答

使用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)

这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况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']

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”

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

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

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

sage: eval('0b'+b)
15

如果你正在寻找与hex()等价的bin(),它是在python 2.6中添加的。

例子:

>>> bin(10)
'0b1010'