其他分享
首页 > 其他分享> > 进制随意转换

进制随意转换

作者:互联网

# 十进制转化为N进制


def func1(s: str, s_base:int, n_base: int):
baselist = '0123456789ABCDEF'
res = str(s)

# 原数不是十进制时,先转为十进制:累加
if s_base != 10:
ssum = 0
s = str(s)[::-1]
for i in range(len(s)):
ssum += baselist.index(s[i]) * s_base ** i
res = str(ssum)

# 转为非十进制:累计求余
if n_base != 10:
temp = []
while res:
temp.append(baselist[int(res) % n_base])
res = int(res) // n_base
res = ''.join(temp[::-1])
return res


if __name__ == '__main__':
source = '233'
s_base = 8
n_base = 10
print(func1(source, s_base, n_base))

标签:随意,__,转换,进制,int,res,base,str,十进制
来源: https://www.cnblogs.com/bigcoolcool/p/16204105.html