# -*- coding: utf-8 -*-
# 10进制转化为任何进制
from string import digits,ascii_lowercase,ascii_uppercase
Alphabat = digits + ascii_lowercase + ascii_uppercase
#print(Alphabat)
## 递归的方法
def ten2any(num,b=64):
# 不满足assert条件的会直接被抛出异常
assert b<=64 and b>1
n,index = divmod(num,b)
if n>0:
return ten2any(n,b) + Alphabat[index]
else:
return Alphabat[index]
## 迭代的方法
def ten2any1(n,b=64):
assert n<=64 and n > 1
res = ""
while n > 0:
n,index = divmod(n)
res = Alphabat[index] + res
return res
### 任何进制转化为10进制
def any2ten(s,base=62):
assert base<=62 and base>1
res = 0
s = str(s)
for i,n in enumerate(reversed(s)):
index = Alphabat.index(n)
res = res + index*pow(base,i)
return res
if __name__ == "__main__":
print(ten2any(16,17))
print(any2ten(16,16))
网友评论