1.python的十进制与任意进制的转换
将任意进制转换成十进制
print(int(\"54\", 8))# 表示把8进制的54转换成十进制数并输出结果。# 8可以是2、8,10,16等进制数
1.1 将十进制转换成任意进制
def f(n,x):a=[0,1,2,3,4,5,6,7,8,9,\'A\',\'B\',\'C\',\'D\',\'E\',\'F\']b=[]while True:s=n//xy=n%xb=b+[y]if s==0:breakn=sfor i in b[::-1]:print(a[i],end=\'\')# b.reverse() 替换成这部分语句也可# for i in b:# print(a[i],end=\'\')f(44,3)
1.3 函数转化进制
将十进制decimal system转换成二进制binary systemprint(bin(10))
将十进制decimal system转换成八进制Octalprint(oct(10))
将十进制decimal system转换成十六进制Hexadecimalprint(hex(10))
2.任意进制转化为10进制
def anyToDecimal(num,n):baseStr = {\"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,\"g\":16,\"h\":17,\"i\":18,\"j\":19}new_num = 0nNum = len(num) - 1for i in num:new_num = new_num + baseStr[i]*pow(n,nNum)nNum = nNum -1print(new_num)anyToDecimal(\'1122\', 3)