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

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


当前回答

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

例子:

>>> bin(10)
'0b1010'

其他回答

计算二进制数:

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 binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

输出:

1010

使用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

由于前面的答案大多使用format(), 这是一个f字符串的实现。

integer = 7
bit_count = 5
print(f'{integer:0{bit_count}b}')

输出:

00111

为了方便起见,这里有python文档中格式化字符串文字的链接:https://docs.python.org/3/reference/lexical_analysis.html#f-strings。

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

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