Home > other >  most efficient way to convert decimal to base 64 using Python
most efficient way to convert decimal to base 64 using Python

Time:04-16

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])))

CodePudding user response:

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)
  • Related