gpt4 book ai didi

python - Base 62 转换

转载 作者:IT老高 更新时间:2023-10-28 21:32:55 33 4
gpt4 key购买 nike

如何将整数转换为以 62 为基数(类似于十六进制,但使用以下数字:'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')。

我一直在尝试为它找到一个好的 Python 库,但它们似乎都忙于转换字符串。 Python base64 模块仅接受字符串并将单个数字转换为四个字符。我正在寻找类似于 URL 缩短器使用的东西。

最佳答案

对此没有标准模块,但我已经编写了自己的函数来实现这一点。

BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def encode(num, alphabet):
"""Encode a positive number into Base X and return the string.

Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
if num == 0:
return alphabet[0]
arr = []
arr_append = arr.append # Extract bound-method for faster access.
_divmod = divmod # Access to locals is faster.
base = len(alphabet)
while num:
num, rem = _divmod(num, base)
arr_append(alphabet[rem])
arr.reverse()
return ''.join(arr)

def decode(string, alphabet=BASE62):
"""Decode a Base X encoded string into the number

Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for decoding
"""
base = len(alphabet)
strlen = len(string)
num = 0

idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1

return num

请注意,您可以为其指定任何字母表以用于编码和解码。如果您不使用 alphabet 参数,您将获得在第一行代码中定义的 62 个字符的字母表,从而对 62 基进行编码/解码。

希望这会有所帮助。

PS - 对于 URL 缩短器,我发现最好省略一些令人困惑的字符,例如 0Ol1oI 等。因此,我使用这个字母表来满足我的 URL 缩短需求 - "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"

玩得开心。

关于python - Base 62 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1119722/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com