在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
计算器与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')
其他回答
n=input()
print(bin(n).replace("0b", ""))
下面是我刚刚实现的代码。这不是一个方法,但你可以把它作为一个现成的函数使用!
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
>>> format(123, 'b')
'1111011'
这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况0不返回任何内容)。
def toBin(num):
if num == 0:
return ""
return toBin(num//2) + str(num%2)
print ([(toBin(i)) for i in range(10)])
['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
计算二进制数:
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