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

其他回答

除非我误解了你所说的二进制字符串,我认为你要找的模块是struct

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

下面是一个使用divmod构造二进制列表的(调试)程序:

程序

while True:
    indecimal_str = input('Enter positive(decimal) integer: ')
    if indecimal_str == '':
        raise SystemExit
    indecimal_save = int(indecimal_str)
    if indecimal_save < 1:
        print('Rejecting input, try again')
        print()
        continue
    indecimal = int(indecimal_str)
    exbin = []
    print(indecimal, '<->', exbin)
    while True:
        if indecimal == 0:
            print('Conversion:', indecimal_save, '=', "".join(exbin))
            print()
            break
        indecimal, r = divmod(indecimal, 2)
        if r == 0:
            exbin.insert(0, '0')
        else:
            exbin.insert(0, '1')
        print(indecimal, '<->', exbin)

输出

Enter positive(decimal) integer: 8
8 <-> []
4 <-> ['0']
2 <-> ['0', '0']
1 <-> ['0', '0', '0']
0 <-> ['1', '0', '0', '0']
Conversion: 8 = 1000

Enter positive(decimal) integer: 63
63 <-> []
31 <-> ['1']
15 <-> ['1', '1']
7 <-> ['1', '1', '1']
3 <-> ['1', '1', '1', '1']
1 <-> ['1', '1', '1', '1', '1']
0 <-> ['1', '1', '1', '1', '1', '1']
Conversion: 63 = 111111

Enter positive(decimal) integer: 409
409 <-> []
204 <-> ['1']
102 <-> ['0', '1']
51 <-> ['0', '0', '1']
25 <-> ['1', '0', '0', '1']
12 <-> ['1', '1', '0', '0', '1']
6 <-> ['0', '1', '1', '0', '0', '1']
3 <-> ['0', '0', '1', '1', '0', '0', '1']
1 <-> ['1', '0', '0', '1', '1', '0', '0', '1']
0 <-> ['1', '1', '0', '0', '1', '1', '0', '0', '1']
Conversion: 409 = 110011001
>>> format(123, 'b')
'1111011'

Python的字符串格式方法可以接受格式规范。

>>> "{0:b}".format(37)
'100101'

Python 2的格式规范文档

Python 3的格式规范文档