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

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


当前回答

n=input()
print(bin(n).replace("0b", ""))

其他回答

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

例子:

>>> bin(10)
'0b1010'

下面是我刚刚实现的代码。这不是一个方法,但你可以把它作为一个现成的函数使用!

def inttobinary(number):
  if number == 0:
    return str(0)
  result =""
  while (number != 0):
      remainder = number%2
      number = number/2
      result += str(remainder)
  return result[::-1] # to invert the string

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

这是针对python3的,它保持前导0 !

print(format(0, '08b'))

备选方案总结:

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。还有马丁·彼得斯。