简体   繁体   中英

most efficient way to convert decimal to base 64 using Python

What is the most efficient way to convert decimal into base 64 (URL friendly) and back.

My current code,

import numpy as np

a = "-0123456789ABCDEFGHIJKLM64OPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
A = {k:i for i,k in enumerate(a)}


def dec_url(x:int, n:int=4):
    o = []
    for i in range(n):
        m = x%(64**(i+1))
        x -= m
        o.append(a[m//(64**i)])
    return ''.join(o[::-1])

def url_dec(s: str):
    return np.sum(map(lambda i:A.get(i[1])*(64**(i[0])),enumerate(s[::-1])))

There are better methods to encode a variable length integer, so for education purposes only:

from functools import reduce

def dec_url(x:int, n:int=4):
    o = []
    while x:
        x, m = divmod(x, 64)
        o.append(a[m])
    return ''.join(reversed(o))

def url_dec(s: str):
    return reduce((lambda total, char: (total << 6) + A[char]), s, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM