所以我正在尝试制作这个 base 10 到 base 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,但由于某种原因它不起作用。我有一个索引错误。我调试了一下,发现在数字数组的第 750 位附近,有一个值为 64 的数字。数字不应该超过 63,这就是为什么没有base64Digits[64]
. 这很奇怪,因为如果数字的值为 64,则意味着前一个数字的值应该定义为 +1,但我不知道是什么导致了这个问题,有人可以帮助我吗?
我的代码没有失败,但是验证它是否正常工作的一个好方法是以几种不同的方式实现算法并进行比较:
# 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)
你的方法和我的方法在五次试验中返回相同的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句