How can I encode an integer with base 36 in Python and then decode it again?
terrible answer, but was just playing around with this an thought i'd share.
import string, math
int2base = lambda a, b: ''.join(
[(string.digits +
string.ascii_lowercase +
string.ascii_uppercase)[(a // b ** i) % b]
for i in range(int(math.log(a, b)), -1, -1)]
)
num = 1412823931503067241
test = int2base(num, 36)
test2 = int(test, 36)
print test2 == num
If you are feeling functional
def b36_encode(i):
if i < 0: return "-" + b36_encode(-i)
if i < 36: return "0123456789abcdefghijklmnopqrstuvwxyz"[i]
return b36_encode(i // 36) + b36_encode(i % 36)
test
n = -919283471029384701938478
s = "-45p3wubacgd6s0fi"
assert int(s, base=36) == n
assert b36_encode(n) == s
from numpy import base_repr
num = base_repr(num, 36)
num = int(num, 36)
Here is information about numpy.base_repr.