您好,请您帮我将denary值转换为二进制和十六进制?我必须输入0到15之间的数字,输出应该是十六进制和二进制等价。这是我到目前为止所做的:
denary_list= ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"]
print("denary list")
binary_list=["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"]
print("binary list")
hex_list=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
print("hex list")
option=input("enter choice:\n1.print values\n2.convert denary number to binary and hex\n3. Convert a hex value between 0 and 15 to denary or binary value\n9. Quit")
if option=='1':
print ("denary","\t","binary","hex")
count1=0
while count1<len(denarylist) and count1<len(binarylist) and count1<len(hexlist):
print(denarylist[count1],"\t",binarylist[count1],"\t",hexlist[count1])
count1+=1
if option=='2':
number=int(input("what number do you choose to convert to binary and hex"))
if number<=15 and number>=0:
答案 0 :(得分:5)
使用format
方法代替b
和x
格式代码将整数格式化为十六进制或二进制数字:
>>> format(1234, 'b')
'10011010010'
>>> format(1234, 'x')
'4d2'
使用int('01234fff', 16)
将十六进制字符串转换为数字;同样int('11110000', 2)
将二进制字符串转换为数字。
并回答您的原始问题:您可以使用binary_list[number]
获得数字项(从零开始编制索引),因此您可以将选项2编写为
number = int(input("what number do you choose to convert to binary and hex"))
if 0 <= number <= 15:
print("the number in binary is", binary_list[number])
print("the number in hex is", hex_list[number])
答案 1 :(得分:1)
这是我自己的二进制转换器的版本:
Number = int(input("Enter a number to convert: "))
if Number < 0:
print ("Can't be less than 0")
else:
Remainder = 0
String = ""
while Number > 0:
Remainder = Number % 2
Number = Number //2
String = str(Remainder) + String
print (String)