python实现正整数的2,8,10,16进制数之间的互相转换

思路

  1. 构造一个10进制转(2,8,16)进制的函数;
  2. 构造一个(2,8,16)进制转10进制的函数;
  3. 操作两个函数,完成2,8,10,16进制数之间的互相转换。

输入注意

  1. 输入8进制和16进制数时,不需要输入‘0o’或‘0x’,输入数字即可。

代码如下

#encoding=utf-8
import math
num=input("请输入一个数字:")
mertic=int(input("请输入该数的进制数:"))
newMertic=int(input("请输入要转化成的进制数:"))
def tenToAny(num,newMertic):
    num=int(num)
    # 初始化输出字符串
    str_New = ""
    if newMertic == 8:
        str_New = "0o"
    if newMertic == 16:
        str_New = "0x"

    if newMertic in [2,8,10,16]:
    #初始化栈
       lists = []
    #while循环,进行入栈操作
       while True:
          remainder = num % newMertic
          if remainder == 10:
                remainder = 'A'
          elif remainder == 11:
                remainder = 'B'
          elif remainder == 12:
                remainder = 'C'
          elif remainder == 13:
                remainder = 'D'
          elif remainder == 14:
                remainder = 'E'
          elif remainder == 15:
                remainder = 'F'
          num = int(num / newMertic)
          lists.append(remainder)#让余数入栈
          if num==0:
                break

       lists.reverse()#倒序排列栈中的元素
       for i in range(len(lists)):
            str_New += str(lists[i])
       return str_New
    else:
       return '输入的‘要转化成’的进制数有误!'


def anyToTen(num,mertic):
    num = list(num)
    # 如果输入一个2,8,10进制且带字母的数,前后矛盾,报错
    for i in num:
        if (i in ['A', 'B', 'C', 'D', 'E', 'F']) and mertic!=16:
            return '输入参数有误!'
    numList = []
    result = 0  # 初始化结果值
    #将16进制中的字母,转化成数字,然后入栈
    for i in range(len(num)):
        if num[i] == 'A':
            num[i] = 10
            numList.append(int(num[i]))
        elif num[i] == 'B':
            num[i] = 11
            numList.append(int(num[i]))
        elif num[i] == 'C':
            num[i] = 12
            numList.append(int(num[i]))
        elif num[i] == 'D':
            num[i] = 13
            numList.append(int(num[i]))
        elif num[i] == 'E':
            num[i] = 14
            numList.append(int(num[i]))
        elif num[i] == 'F':
            num[i] = 15
            numList.append(int(num[i]))
        else:
            numList.append(int(num[i]))

    numList.reverse()#倒序排列栈中的元素
    #栈中元素和进制数,计算出结果
    if mertic in [2, 8, 10, 16]:
        for i in range(len(numList)):
            result += numList[i] * math.pow(mertic, i)
        return result
    else:
        return "输入的“转化成”的进制数有误!"
#如果“该数”的进制数为10,只调用tenToAny方法
if mertic==10:
    result=tenToAny(num,newMertic)
#如果“转化成”的进制数为10,只调用anyToTen方法
elif newMertic==10:
    result=anyToTen(num,mertic)
#否则,先调用anyToTen方法,再调用tenToAny方法
else:
    mid=anyToTen(num,mertic)
    result=tenToAny(mid,newMertic)
print(result)

感想: 欢迎大家与我一起讨论,优化代码!

你可能感兴趣的:(python)