Python learning algorithm: Any hex conversion

Python arbitrary binary conversion

A is given a binary number N, you have it turn into a B band.

Input
first line two integers A, B (2 <= A , B <= 16)

A second line is a hexadecimal string N. A hexadecimal number N Title ensure rotation in a range in the decimal range inti type.

If A> = 10, and the weight of some 10 bits or greater, then the weight value is represented by lower case letters, for example, representatives of A 10, representative of BB 11, c representatives 12, d representatives 13, e 14 on behalf of the representative f 15.

Output
Output converted into N-ary B results.

输入
10 2
100
输出
1100100
输入
2 16
10001111
输出
8f
def f(n, x):
    #n为待转换的十进制数,x为机制,取值为2-16
    a=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
    b=[]
    while True:
        s=n // x  # 商
        y=n % x  # 余数
        b=b+[y]
        if s==0:
            break
        n=s
    b.reverse() # 辗转相除法
    ans = ''
    for i in b:
        ans += str(a[i]) 
    return ans

A,B = map(int, input().split())
n = int(input())
n = int(str(n), A) # int函数可以将A进制的n统一转为十进制
ans = f(n, B)
print(ans)
Published 126 original articles · won praise 35 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43442524/article/details/104465886