python - Base 62 转换

标签 python math base62

如何将整数转换为以 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/

相关文章:

python - 编程面试要素中的死锁题19.5

java - 在 Java 中将 UUID 编码为 Base62(而非 Base64)

python - 着色问题 - open cv 与 matplotlib legend 的结合

Python电话类---打印无

javascript - 为什么这些 JavaScript 方程会输出不同(但几乎相同)的答案?

math - 在没有浮点类型的javacard中计算sqrt和arcTan

java - JAVA 和 Delphi 中的数学函数给出不同的结果

java - 在保留唯一性的同时缩短 java UUID

javascript - 如何在 node.js 中生成 base62 UUID?

python - 我会称之为高级元组操作吗?