基地62转换

时间:2009-07-13 14:19:42

标签: python math base62

如何将整数转换为基数62(如十六进制,但使用这些数字:'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')。

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

22 个答案:

答案 0 :(得分:140)

没有标准模块,但我已经编写了自己的功能来实现这一目标。

BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def encode(num, alphabet=BASE62):
    """Encode a positive number in Base X

    Arguments:
    - `num`: The number to encode
    - `alphabet`: The alphabet to use for encoding
    """
    if num == 0:
        return alphabet[0]
    arr = []
    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 encoding
    """
    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等。因此,我使用此字母表来缩短网址缩短需求 - "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"

玩得开心。

答案 1 :(得分:43)

我曾经写过一个脚本来做这件事,我认为这很优雅:)

import string
BASE_LIST = string.digits + string.letters + '_@'
BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST))

def base_decode(string, reverse_base=BASE_DICT):
    length = len(reverse_base)
    ret = 0
    for i, c in enumerate(string[::-1]):
        ret += (length ** i) * reverse_base[c]

    return ret

def base_encode(integer, base=BASE_LIST):
    if integer == 0:
        return base[0]

    length = len(base)
    ret = ''
    while integer != 0:
        ret = base[integer % length] + ret
        integer /= length

    return ret

使用示例:

for i in range(100):                                    
    print i, base_decode(base_encode(i)), base_encode(i)

答案 2 :(得分:8)

以下解码器制造商可以使用任何合理的基础,具有更加整洁的循环,并在遇到无效字符时给出明确的错误消息。

def base_n_decoder(alphabet):
    """Return a decoder for a base-n encoded string
    Argument:
    - `alphabet`: The alphabet used for encoding
    """
    base = len(alphabet)
    char_value = dict(((c, v) for v, c in enumerate(alphabet)))
    def f(string):
        num = 0
        try:
            for char in string:
                num = num * base + char_value[char]
        except KeyError:
            raise ValueError('Unexpected character %r' % char)
        return num
    return f

if __name__ == "__main__":
    func = base_n_decoder('0123456789abcdef')
    for test in ('0', 'f', '2020', 'ffff', 'abqdef'):
        print test
        print func(test)

答案 3 :(得分:7)

如果您正在寻找最高效率(如django),您将需要以下内容。此代码是Baishampayan Ghose和WoLpH以及John Machin的有效方法的组合。

# Edit this list of characters as desired.
BASE_ALPH = tuple("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_ALPH))
BASE_LEN = len(BASE_ALPH)

def base_decode(string):
    num = 0
    for char in string:
        num = num * BASE_LEN + BASE_DICT[char]
    return num

def base_encode(num):
    if not num:
        return BASE_ALPH[0]

    encoding = ""
    while num:
        num, rem = divmod(num, BASE_LEN)
        encoding = BASE_ALPH[rem] + encoding
    return encoding

您可能还想提前计算字典。 (注意:使用字符串进行编码比使用列表更有效率,即使数字非常长。)

>>> timeit.timeit("for i in xrange(1000000): base.base_decode(base.base_encode(i))", setup="import base", number=1)
2.3302059173583984

在2.5秒内编码并解码100万个数字。 (2.2Ghz i7-2670QM)

答案 4 :(得分:4)

你可能想要base64,而不是base62。它有一个与URL兼容的版本,所以额外的两个填充字符应该不是问题。

这个过程相当简单;考虑base64表示6位,常规字节表示8.将000000到111111的值分配给所选的64个字符中的每一个,并将4个值放在一起以匹配一组3个base256字节。对每组3个字节重复一次,最后填充,选择填充字符(0通常很有用)。

答案 5 :(得分:3)

如果你只需要生成一个简短的ID(因为你提到URL缩短器)而不是编码/解码某些东西,这个模块可能有所帮助:

https://github.com/stochastic-technologies/shortuuid/

答案 6 :(得分:2)

您可以从pypi

下载zbase62模块

例如

>>> import zbase62
>>> zbase62.b2a("abcd")
'1mZPsa'

答案 7 :(得分:2)

如果使用django框架,则可以使用django.utils.baseconv模块。

>>> from django.utils import baseconv
>>> baseconv.base62.encode(1234567890)
1LY7VK

除了base62之外,baseconv还定义了base2 / base16 / base36 / base56 / base64。

答案 8 :(得分:2)

我从这里的其他人的帖子中受益匪浅。我最初需要用于Django项目的python代码,但从那以后我转向了node.js,所以这里是代码的 javascript版本 (编码部分) Baishampayan Ghose提供。

var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

function base62_encode(n, alpha) {
  var num = n || 0;
  var alphabet = alpha || ALPHABET;

  if (num == 0) return alphabet[0];
  var arr = [];
  var base = alphabet.length;

  while(num) {
    rem = num % base;
    num = (num - rem)/base;
    arr.push(alphabet.substring(rem,rem+1));
  }

  return arr.reverse().join('');
}

console.log(base62_encode(2390687438976, "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"));

答案 9 :(得分:2)

这是我的解决方案:

def base62(a):
    baseit = (lambda a=a, b=62: (not a) and '0' or
        baseit(a-a%b, b*62) + '0123456789abcdefghijklmnopqrstuvwxyz'
                              'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%b%61 or -1*bool(a%b)])
    return baseit()

解释

在任何基数中,每个数字都等于a1+a2*base**2+a3*base**3...所以目标是找到所有a

对于每N=1,2,3...代码,代码将aN*base**N隔离bb=base**(N+1) a隔离所有N s大于a每当函数被当前N递归调用时,通过递减a来切割所有aN*base**N以使其序列小于Base%(base-1)==1

base**p%(base-1)==1因此q*base^p%(base-1)==q因此q==base-1只有一个例外,当0返回0时。要解决这种情况,它会返回0。该函数从头开始检查loc

优点

在这个样本中,只有一个乘法(而不是除法)和一些模数运算,它们都相对较快。

答案 10 :(得分:2)

我希望以下代码段可以提供帮助。

def num2sym(num, sym, join_symbol=''):
    if num == 0:
        return sym[0]
    if num < 0 or type(num) not in (int, long):
        raise ValueError('num must be positive integer')

    l = len(sym)  # target number base
    r = []
    div = num
    while div != 0: # base conversion
        div, mod = divmod(div, l)
        r.append(sym[mod])

    return join_symbol.join([x for x in reversed(r)])

您案件的用法:

number = 367891
alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print num2sym(number, alphabet)  # will print '1xHJ'

显然,您可以指定另一个字母,由更少或更多数量的符号组成,然后它会将您的数字转换为更小或更大的数字基数。例如,将'01'作为字母表输出将输出表示输入数字的字符串作为二进制。

您最初可能会对字母进行随机播放,以获得数字的唯一表示形式。如果您正在制作URL缩短服务,这会很有帮助。

答案 11 :(得分:1)

我写了一段时间后,它的效果非常好(负面和所有包括在内)

def code(number,base):
    try:
        int(number),int(base)
    except ValueError:
        raise ValueError('code(number,base): number and base must be in base10')
    else:
        number,base = int(number),int(base)
    if base < 2:
        base = 2
    if base > 62:
        base = 62
    numbers = [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"]
    final = ""
    loc = 0
    if number < 0:
        final = "-"
        number = abs(number)
    while base**loc <= number:
        loc = loc + 1
    for x in range(loc-1,-1,-1):
        for y in range(base-1,-1,-1):
            if y*(base**x) <= number:
                final = "{}{}".format(final,numbers[y])
                number = number - y*(base**x)
                break
    return final

def decode(number,base):
    try:
        int(base)
    except ValueError:
        raise ValueError('decode(value,base): base must be in base10')
    else:
        base = int(base)
    number = str(number)
    if base < 2:
        base = 2
    if base > 62:
        base = 62
    numbers = ["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"]
    final = 0
    if number.startswith("-"):
        neg = True
        number = list(number)
        del(number[0])
        temp = number
        number = ""
        for x in temp:
            number = "{}{}".format(number,x)
    else:
        neg = False
    loc = len(number)-1
    number = str(number)
    for x in number:
        if numbers.index(x) > base:
            raise ValueError('{} is out of base{} range'.format(x,str(base)))
        final = final+(numbers.index(x)*(base**loc))
        loc = loc - 1
    if neg:
        return -final
    else:
        return final

抱歉所有的长度

答案 12 :(得分:1)

现在有一个python库。

我正在为此制作一个pip包。

我建议您使用受bases.js启发的bases.py https://github.com/kamijoutouma/bases.py

from bases import Bases
bases = Bases()

bases.toBase16(200)                // => 'c8'
bases.toBase(200, 16)              // => 'c8'
bases.toBase62(99999)              // => 'q0T'
bases.toBase(200, 62)              // => 'q0T'
bases.toAlphabet(300, 'aAbBcC')    // => 'Abba'

bases.fromBase16('c8')               // => 200
bases.fromBase('c8', 16)             // => 200
bases.fromBase62('q0T')              // => 99999
bases.fromBase('q0T', 62)            // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300

参考https://github.com/kamijoutouma/bases.py#known-basesalphabets 什么基地可用

答案 13 :(得分:1)

这是一种递归和迭代的方法。根据执行次数,迭代的速度会快一些。

def base62_encode_r(dec):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return s[dec] if dec < 62 else base62_encode_r(dec / 62) + s[dec % 62]
print base62_encode_r(2347878234)

def base62_encode_i(dec):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ret = ''
    while dec > 0:
        ret = s[dec % 62] + ret
        dec /= 62
    return ret
print base62_encode_i(2347878234)

def base62_decode_r(b62):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if len(b62) == 1:
        return s.index(b62)
    x = base62_decode_r(b62[:-1]) * 62 + s.index(b62[-1:]) % 62
    return x
print base62_decode_r("2yTsnM")

def base62_decode_i(b62):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ret = 0
    for i in xrange(len(b62)-1,-1,-1):
        ret = ret + s.index(b62[i]) * (62**(len(b62)-i-1))
    return ret
print base62_decode_i("2yTsnM")

if __name__ == '__main__':
    import timeit
    print(timeit.timeit(stmt="base62_encode_r(2347878234)", setup="from __main__ import base62_encode_r", number=100000))
    print(timeit.timeit(stmt="base62_encode_i(2347878234)", setup="from __main__ import base62_encode_i", number=100000))
    print(timeit.timeit(stmt="base62_decode_r('2yTsnM')", setup="from __main__ import base62_decode_r", number=100000))
    print(timeit.timeit(stmt="base62_decode_i('2yTsnM')", setup="from __main__ import base62_decode_i", number=100000))

0.270266867033
0.260915645986
0.344734796766
0.311662500262

答案 14 :(得分:1)

BASE_LIST = tuple("23456789ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz")
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_LIST))
BASE_LEN = len(BASE_LIST)

def nice_decode(str):
    num = 0
    for char in str[::-1]:
        num = num * BASE_LEN + BASE_DICT[char]
    return num

def nice_encode(num):
    if not num:
        return BASE_LIST[0]

    encoding = ""
    while num:
        num, rem = divmod(num, BASE_LEN)
        encoding += BASE_LIST[rem]
    return encoding

答案 15 :(得分:1)

我个人喜欢Baishampayan的解决方案,主要是因为剥离了令人困惑的角色。

为了完整性和性能更好的解决方案,this post显示了使用Python base64模块的方法。

答案 16 :(得分:0)

原始 javascript 版本:

var hash = "", alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", alphabetLength = 
alphabet.length;
do {
  hash = alphabet[input % alphabetLength] + hash;
  input = parseInt(input / alphabetLength, 10);
} while (input);

来源:https://hashids.org/

蟒蛇:

def to_base62(number):
  alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  alphabetLength = len(alphabet)
  result = ""
  while True:
    result = alphabet[number % alphabetLength] + result
    number = int(number / alphabetLength)
    if number == 0:
      break
  return result

print to_base62(59*(62**2) + 60*(62) + 61)
# result: XYZ

答案 17 :(得分:0)

适用于 Python3 的基准测试答案(机器:i7-8565U):

"""
us per enc()+dec()  #  test

(4.477935791015625, 2, '3Tx16Db2JPSS4ZdQ4dp6oW')
(6.073190927505493, 5, '3Tx16Db2JPSS4ZdQ4dp6oW')
(9.051250696182251, 9, '3Tx16Db2JPSS4ZdQ4dp6oW')
(9.864609956741333, 6, '3Tx16Db2JOOqeo6GCGscmW')
(10.868197917938232, 1, '3Tx16Db2JPSS4ZdQ4dp6oW')
(11.018349647521973, 10, '3Tx16Db2JPSS4ZdQ4dp6oW')
(12.448230504989624, 4, '03Tx16Db2JPSS4ZdQ4dp6oW')
(13.016672611236572, 7, '3Tx16Db2JPSS4ZdQ4dp6oW')
(13.212724447250366, 8, '3Tx16Db2JPSS4ZdQ4dp6oW')
(24.119479656219482, 3, '3tX16dB2jpss4zDq4DP6Ow')
"""

from time import time

half = 2 ** 127
results = []


def bench(n, enc, dec):
    start = time()
    for i in range(half, half + 1_000_000):
        dec(enc(i))
    end = time()
    results.append(tuple([end - start, n, enc(half + 1234134134134314)]))


BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def encode(num, alphabet=BASE62):
    """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


bench(1, encode, decode)
###########################################################################################################
# Remove the `_@` below for base62, now it has 64 characters
BASE_ALPH = tuple(BASE62)
BASE_LIST = BASE62
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_ALPH))

###########################################################################################################
BASE_LEN = len(BASE_ALPH)


def decode(string):
    num = 0
    for char in string:
        num = num * BASE_LEN + BASE_DICT[char]
    return num


def encode(num):
    if not num:
        return BASE_ALPH[0]

    encoding = ""
    while num:
        num, rem = divmod(num, BASE_LEN)
        encoding = BASE_ALPH[rem] + encoding
    return encoding


bench(2, encode, decode)

###########################################################################################################
from django.utils import baseconv

bench(3, baseconv.base62.encode, baseconv.base62.decode)


###########################################################################################################
def encode(a):
    baseit = (lambda a=a, b=62: (not a) and '0' or
                                baseit(a - a % b, b * 62) + '0123456789abcdefghijklmnopqrstuvwxyz'
                                                            'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[
                                    a % b % 61 or -1 * bool(a % b)])
    return baseit()


bench(4, encode, decode)


###########################################################################################################
def encode(num, sym=BASE62, join_symbol=''):
    if num == 0:
        return sym[0]

    l = len(sym)  # target number base
    r = []
    div = num
    while div != 0:  # base conversion
        div, mod = divmod(div, l)
        r.append(sym[mod])

    return join_symbol.join([x for x in reversed(r)])


bench(5, encode, decode)

###########################################################################################################
from math import floor

base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
b = 62;


def decode(b62: str) -> int:
    limit = len(b62)
    res = 0
    for i in range(limit):
        res = b * res + base.find(b62[i])
    return res


def encode(b10: int) -> str:
    if b <= 0 or b > 62:
        return 0
    r = b10 % b
    res = base[r];
    q = floor(b10 / b)
    while q:
        r = q % b
        q = floor(q / b)
        res = base[int(r)] + res
    return res


bench(6, encode, decode)


###########################################################################################################
def encode(dec):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return s[dec] if dec < 62 else encode(dec // 62) + s[int(dec % 62)]


def decode(b62):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if len(b62) == 1:
        return s.index(b62)
    x = decode(b62[:-1]) * 62 + s.index(b62[-1:]) % 62
    return x


bench(7, encode, decode)


def encode(dec):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ret = ''
    while dec > 0:
        ret = s[dec % 62] + ret
        dec //= 62
    return ret


def decode(b62):
    s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ret = 0
    for i in range(len(b62) - 1, -1, -1):
        ret = ret + s.index(b62[i]) * (62 ** (len(b62) - i - 1))
    return ret


bench(8, encode, decode)


###########################################################################################################

def encode(num):
    s = ""
    while num > 0:
        num, r = divmod(num, 62)
        s = BASE62[r] + s
    return s


def decode(num):
    x, s = 1, 0
    for i in range(len(num) - 1, -1, -1):
        s = int(BASE62.index(num[i])) * x + s
        x *= 62
    return s


bench(9, encode, decode)


###########################################################################################################

def encode(number: int, alphabet=BASE62, padding: int = 22) -> str:
    l = len(alphabet)
    res = []
    while number > 0:
        number, rem = divmod(number, l)
        res.append(alphabet[rem])
        if number == 0:
            break
    return "".join(res)[::-1]  # .rjust(padding, "0")


def decode(digits: str, lookup=BASE_DICT) -> int:
    res = 0
    last = len(digits) - 1
    base = len(lookup)
    for i, d in enumerate(digits):
        res += lookup[d] * pow(base, last - i)
    return res


bench(10, encode, decode)

###########################################################################################################

for row in sorted(results):
    print(row)

答案 18 :(得分:0)

最简单的

BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode_base62(num):
    s = ""
    while num>0:
      num,r = divmod(num,62)
      s = BASE62[r]+s
    return s


def decode_base62(num):
   x,s = 1,0
   for i in range(len(num)-1,-1,-1):
      s = int(BASE62.index(num[i])) *x + s
      x*=62
   return s

print(encode_base62(123))
print(decode_base62("1Z"))

答案 19 :(得分:0)

Python 3.7.x

我在寻找existing base62 script时发现了博士学位的github,其中包含一些算法。目前,它不适用于当前的Python 3的max-version版本,因此我继续进行并固定在需要的地方,并进行了一些重构。我通常不使用Python,并且总是临时使用它,因此YMMV。所有功劳归于Dr. Zhihua Lai。我只是解决了这个版本的Python。

文件base62.py

#modified from Dr. Zhihua Lai's original on GitHub
from math import floor
base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
b = 62;
def toBase10(b62: str) -> int:
    limit = len(b62)
    res = 0
    for i in range(limit):
        res = b * res + base.find(b62[i])
    return res
def toBase62(b10: int) -> str:
    if b <= 0 or b > 62:
        return 0
    r = b10 % b
    res = base[r];
    q = floor(b10 / b)
    while q:
        r = q % b
        q = floor(q / b)
        res = base[int(r)] + res
    return res

文件try_base62.py

import base62
print("Base10 ==> Base62")
for i in range(999):
    print(f'{i} => {base62.toBase62(i)}')
base62_samples = ["gud", "GA", "mE", "lo", "lz", "OMFGWTFLMFAOENCODING"]
print("Base62 ==> Base10")
for i in range(len(base62_samples)):
    print(f'{base62_samples[i]} => {base62.toBase10(base62_samples[i])}')

try_base62.py

的输出
  

Base10 ==> Base62
  0 => 0
  [...]
  998 => g6
  Base62 ==> Base10
  gud => 63377
  GA => 2640
  mE => 1404
  lo => 1326
  lz => 1337
  OMFGWTFLMFAOENCODING => 577002768656147353068189971419611424

由于回购中没有许可信息,所以我提交了PR,因此原始作者至少知道其他人正在使用和修改他们的代码。

答案 20 :(得分:0)

简单的递归

"""
This module contains functions to transform a number to string and vice-versa
"""
BASE = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
LEN_BASE = len(BASE)


def encode(num):
    """
    This function encodes the given number into alpha numeric string
    """

    if num < LEN_BASE:
        return BASE[num]

    return BASE[num % LEN_BASE] + encode(num//LEN_BASE)


def decode_recursive(string, index):
    """
    recursive util function for decode
    """

    if not string or index >= len(string):
        return 0

    return (BASE.index(string[index]) * LEN_BASE ** index) + decode_recursive(string, index + 1)


def decode(string):
    """
    This function decodes given string to number
    """

    return decode_recursive(string, 0)

答案 21 :(得分:0)

抱歉,我在这里无法帮助您使用图书馆。我更喜欢使用base64,只是添加额外的字符给你选择 - 如果可能的话!

然后你可以使用base64模块。

如果确实如此,那真的不可能:

你可以这样做(这是伪代码):

base62vals = []
myBase = 62
while num > 0:
   reminder = num % myBase
   num = num / myBase
   base62vals.insert(0, reminder)