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

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


当前回答

你可以这样做:

bin(10)[2:]

or :

f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c

其他回答

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

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

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

Python 2的格式规范文档

Python 3的格式规范文档

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

计算二进制数:

print("Binary is {0:>08b}".format(16))

计算一个数的十六进制小数:

print("Hexa Decimal is {0:>0x}".format(15))

计算所有的二进制直到16::

for i in range(17):
   print("{0:>2}: binary is {0:>08b}".format(i))

要计算十六进制小数,直到17

 for i in range(17):
    print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
##as 2 digit is enogh for hexa decimal representation of a 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。还有马丁·彼得斯。