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

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


当前回答

我很惊讶,没有提到一个很好的方法来实现这一点,使用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'

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

其他回答

与Yusuf Yazici的回答相似

def intToBin(n):
    if(n < 0):
        print "Sorry, invalid input."
    elif(n == 0):
        print n
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n /= 2
        print result[::-1]

我调整了它,使唯一被改变的变量是结果(当然还有n)。

如果你需要在其他地方使用这个函数(即,让结果被另一个模块使用),考虑以下调整:

def intToBin(n):
    if(n < 0):
        return -1
    elif(n == 0):
        return str(n)
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n //= 2            #added integer division
        return result[::-1]

因此-1将是表示转换失败的哨兵值。(这是假设您只转换正数,无论它们是整数还是长数)。

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

备选方案总结:

n=42
assert  "-101010" == format(-n, 'b')
assert  "-101010" == "{0:b}".format(-n)
assert  "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
assert "0b101010" == bin(n)
assert   "101010" == bin(n)[2:]   # But this won't work for negative numbers.

贡献者包括John Fouhy, Tung Nguyen, mVChr, Martin Thoma。还有马丁·彼得斯。

>>> format(123, 'b')
'1111011'

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