思路是所有原始数制转换成十进制,然后从十进制转换成目标进制:
def fun_any_to_d(n, b): # any to decimal(n : number system, b : operand)
a = str(b)
list = []
for i in a:
list.append(hex_switch.get(i, "False"))
for x in list:
if x not in range(n) :
return "invalid number"
sum = 0
for i in list:
sum = sum * n + int(i)
return sum
def fun_d_to_any(n, b): # decimal to any
a = str(b)
mod = int(a) % n
var = int(a) // n
bir = str(mod)
while var != 0:
mod = var % n
bir = str(mod) + bir
var = var // n
int_bir = int(bir)
return int_bir
def fun_any_to_any(origin, expection, oper):# any to any
temp = fun_any_to_d(origin, oper)
if temp != "invalid number":
return fun_d_to_any(expection, temp)
if temp == "invalid number":
return temp
def fun_sysconvert(): # sys convert
while True:
origin = int(input("please enter the original number system(2,8,10,16):"))
expection = int(input("please enter the number system you want to get(2,8,10,16):"))
oper = input("please enter the number to convert:")
print("the result is:")
print(fun_any_to_any(origin, expection, oper))
hex_switch = {
# hex switch 十六进制数查表
'0':0,
'1':1,
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'9':9,
'A':10,
'B':11,
'C':12,
'D':13,
'E':14,
'F':15,
'a':10,
'b':11,
'c':12,
'd':13,
'e':14,
'f':15,}
fun_sysconvert() # mian fun