函数 returns 表示 python 中 n 的基数 b 表示的一串数字

Function that returns a string of digits that represent the base b representation of n in python

我有:

def d2x(n, b):
    res = ""
    while n != 0 :
        res = n % b + res
        n = n / b
    return res

示例输出:

d2x(10,2)
    '1010' 
d2x(10,3)
    '101'
d2x(10,8)
    '12'

老实说,我迷路了。感谢任何帮助。

这将适用于 16 进制....

#convert base 10 to any base between 2 and 16
def convBase(n, base):
    charSeq = '0123456789ABCDEF'
    if n < base:
        return charSeq[n]
    else:
        return convBase(n//base, base) + charSeq[n%base]

#print convBase(10,16)