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

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


当前回答

计算二进制数:

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

其他回答

作为参考:

def toBinary(n):
    return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])

这个函数可以将一个正整数一样大18446744073709551615,表示为字符串“1111111111111111111111111111111111111111111111111111111111111111”。

它可以被修改为一个更大的整数,尽管它可能不像"{0:b}".format()或bin()那么方便。

备选方案总结:

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

Python 3.6增加了一种新的字符串格式化方法,称为格式化字符串字面量或“f-strings”。 例子:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

输出将是“你好,Bob,您的号码是00001010!”

关于这个问题的讨论可以在这里找到-在这里

这是我的答案,它工作得很好…!

def binary(value) :
    binary_value = ''
    while value !=1  :
        binary_value += str(value%2)
        value = value//2
    return '1'+binary_value[::-1]

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”