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

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


当前回答

下面是一个使用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

其他回答

对于那些需要将有符号整数(范围-2**(digits-1)到2**(digits-1)-1)转换为2的补码二进制字符串的人来说,这是可行的:

def int2bin(integer, digits):
    if integer >= 0:
        return bin(integer)[2:].zfill(digits)
    else:
        return bin(2**digits + integer)[2:]

这产生:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'
>>> format(123, 'b')
'1111011'

我很惊讶,没有提到一个很好的方法来实现这一点,使用Python 3.6及更高版本支持的格式化字符串。TLDR:

>>> number = 1
>>> f'0b{number:08b}'
'0b00000001'

长故事

这是Python 3.6提供的格式化字符串的功能:

>>> x, y, z = 1, 2, 3
>>> f'{x} {y} {2*z}'
'1 2 6'

你也可以请求二进制文件:

>>> f'{z:b}'
'11'

指定宽度:

>>> f'{z:8b}'
'      11'

请求零填充:

f'{z:08b}'
'00000011'

并添加公共前缀表示二进制数:

>>> f'0b{z:08b}'
'0b00000011'

你也可以让Python为你添加前缀,但我不喜欢上面的版本,因为你必须把前缀考虑到宽度:

>>> f'{z:#010b}'
'0b00000011'

更多信息可在格式化字符串文字和格式规范迷你语言的官方文档中获得。

使用lambda的一行代码:

>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)

测试:

>>> binary(5)
'101'

编辑:

但是接下来:(

t1 = time()
for i in range(1000000):
     binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922

在比较中

t1 = time()
for i in range(1000000):
    '{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232

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”