Skip to content

Instantly share code, notes, and snippets.

@phikal
Last active October 24, 2015 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phikal/21c30b75245566989956 to your computer and use it in GitHub Desktop.
Save phikal/21c30b75245566989956 to your computer and use it in GitHub Desktop.
BINARY = '01'
OCTAL = '01234567'
DECIMAL = '0123456789'
HEXADEC = '0123456789ABCDEF'
BASE_62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
rev = lambda x: dict((c, i) for i, c in enumerate(x))
used = BASE_62
def encode(NUM, base=used):
ret = ''
factor = ''
blen = len(base)
if NUM < 0:
NUM *= -1
factor = '-'
while NUM != 0:
ret += base[NUM % blen]
NUM //= blen
return factor + ret[::-1]
def decode(STR, base=used):
ret = 0
factor = 1
rbase = rev(base)
blen = len(base)
if STR[0] == '-':
STR = STR[1:]
factor = -1
for i, c in enumerate(reversed(STR)):
ret += (blen ** i) * rbase[c]
return factor * ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment