在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

其他回答

这是一个简单的连续循环的二进制到十进制转换器

t = 1
while t > 0:
    binaryNumber = input("Enter a binary No.")
    convertedNumber = int(binaryNumber, 2)

    print(convertedNumber)

print("")

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

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

Python 2的格式规范文档

Python 3的格式规范文档

如果你正在寻找与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

计算器与DEC,BIN,HEX的所有必要功能: (使用Python 3.5制作和测试)

您可以更改输入的测试数字并获得转换后的数字。

# CONVERTER: DEC / BIN / HEX

def dec2bin(d):
    # dec -> bin
    b = bin(d)
    return b

def dec2hex(d):
    # dec -> hex
    h = hex(d)
    return h

def bin2dec(b):
    # bin -> dec
    bin_numb="{0:b}".format(b)
    d = eval(bin_numb)
    return d,bin_numb

def bin2hex(b):
    # bin -> hex
    h = hex(b)
    return h

def hex2dec(h):
    # hex -> dec
    d = int(h)
    return d

def hex2bin(h):
    # hex -> bin
    b = bin(h)
    return b


## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111 
numb_hex = 0xFF


## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)

res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)

res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)



## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin:    ',res_dec2bin,'\nhex:    ',res_dec2hex,'\n')

print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec:    ',numb_bin,'\nhex:    ',res_bin2hex,'\n')

print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin:    ',res_hex2bin,'\ndec:    ',res_hex2dec,'\n')