Python:如何将文件转换为自定义基数并返回?

Python: How do I convert file to custom base number and back?

我有一个文件要转换为自定义基数(例如,基数 86,带有自定义字母表)

我已经尝试使用 hexlify 转换文件,然后将其转换为我的自定义基础,但它太慢了...60 Ko 需要 8 秒..

def HexToBase(Hexa, AlphabetList, OccurList, threshold=10):
    number = int(Hexa,16) #base 16 vers base 10
    alphabet = GetAlphabet(AlphabetList, OccurList, threshold)
    #GetAlphabet return a list of all chars that occurs more than threshold times

    b_nbr = len(alphabet) #get the base
    out = ''
    while number > 0:
        out = alphabet[(number % b_nbr)] + out
        number = number // b_nbr
    return out

file = open("File.jpg","rb")
binary_data = file.read()
HexToBase(binascii.hexlify(binary_data),['a','b'],[23,54])

那么,谁能帮我找到正确的解决方案?

抱歉我的英语不好,我是法国人,谢谢你的帮助!

首先你可以替换:

int(binascii.hexlify(binary_data), 16) # timeit: 14.349809918712538

作者:

int.from_bytes(binary_data, byteorder='little') # timeit: 3.3330371951720164

其次可以使用divmod函数加速循环:

out = ""
while number > 0:
    number, m = divmod(number, b_nbr)
    out = alphabet[m] + out

# timeit: 3.8345545611298126 vs 7.472579440019706

对于 divmod%, // 的比较和大数,请参阅

(备注:我预计构建一个数组然后使用 "".join 生成字符串会比 out = ... + out 更快,但 CPython 3.6 并非如此。)

所有的东西放在一起给了我 6 的加速因子。