【问题标题】:Python Denary to Binary ConvertorPython Denary 到二进制转换器
【发布时间】:2015-05-02 04:37:15
【问题描述】:

您好,您能帮我将十进制值转换为二进制和十六进制吗?我必须输入一个介于 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:

【问题讨论】:

  • 你在纠结什么?在我看来,您需要做的只是代码末尾的print binary_list[num]print hex_list[num]
  • 是的,就是这样!谢谢!

标签: python binary


【解决方案1】:

使用format 方法代替bx 格式代码将整数格式化为十六进制或二进制数:

>>> 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])

【讨论】:

  • 感谢您的回复,我是编程新手,这就是我需要的:(使用二进制和十六进制数字列表 - 对于此选项,输入 0 到 15 之间的数字并输出二进制和十六进制等效)您的建议是否足够?
【解决方案2】:

这是我自己的拒绝到二进制转换器的版本:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2021-01-26
    • 2020-06-25
    • 2012-05-28
    • 2013-05-14
    • 2021-07-29
    • 2021-01-03
    相关资源
    最近更新 更多