在python中如何将数字转换为以64为基数的数字?

2024-09-28 01:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着把这个10进制到64进制的转换器做出来,对我来说一切都很好。你知道吗

# digits that will represent the base 64 number
base64Digits = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','-','!']

def base10to64converter(num):

    # Define the number of digits the result will have (limit of 2k)
    i = 1
    while i<2000:
        if num<64**i:
            digitNum = i
            i+=2000
        i+=1

    digits = []

    # calculate the number
    while digitNum > 0:
        digits.append(num // (64**(digitNum-1)))
        num %= (64**(digitNum-1))
        digitNum-=1

    result = ''
    j = 0

    # transform the digits stored in the array into an string
    while j < len(digits):
        result += base64Digits[digits[j]]
        j+=1

    return result

但是我想用大的数字,所以我试着用大的数字。我开始尝试10^2000。成功了。没什么奇怪的,但后来我试了10^2000-1,不知什么原因它不起作用。我有个索引错误。 我稍微调试了一下,发现在digits数组的第750位附近,有一个值为64的数字。数字不应该超过63,这就是为什么没有base64Digits[64]。 这很奇怪,因为如果这个数字的值是64,那么就意味着previus数字的值应该是+1,但是我不知道是什么导致了这个问题,有人能帮我吗?你知道吗


Tags: ofthenumberbasethatdef数字result
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:37

我没有发现您的代码失败,但是验证它是否正常工作的一个好方法是用几种不同的方法实现算法并进行比较:

# digits that will represent the base 64 number
base64Digits = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','-','!']

def base10to64converter(num):

    # Define the number of digits the result will have (limit of 2k)
    i = 1
    while i<2000:
        if num<64**i:
            digitNum = i
            i+=2000
        i+=1

    digits = []

    # calculate the number
    while digitNum > 0:
        digits.append(num // (64**(digitNum-1)))
        num %= (64**(digitNum-1))
        digitNum-=1

    result = ''
    j = 0

    # transform the digits stored in the array into an string
    while j < len(digits):
        result += base64Digits[digits[j]]
        j+=1

    return result

def alternate(n):
    if n < 0:
        raise ValueError('negative numbers not supported')
    base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-!'
    digits = []
    while n != 0:
        n,r = divmod(n,64)
        digits.append(base[r])
    if not digits:
        return '0'
    return ''.join(reversed(digits))

trials = [0,1,64,10**2000-1,10**2000]
for trial in trials:
    n = base10to64converter(trial)
    print(n)
    assert n == alternate(trial)

你的方法和我的方法在五次试验中都得到了相同的答案。你知道吗

相关问题 更多 >

    热门问题