Skip to content

Instantly share code, notes, and snippets.

@lerry
Created July 16, 2013 05:08
Show Gist options
  • Save lerry/6005940 to your computer and use it in GitHub Desktop.
Save lerry/6005940 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import string
ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \
string.digits + '-_'
ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'
def num_encode(n):
if n < 0:
return SIGN_CHARACTER + num_encode(-n)
s = []
while True:
n, r = divmod(n, BASE)
s.append(ALPHABET[r])
if n == 0:
break
return ''.join(reversed(s))
def num_decode(s):
if s[0] == SIGN_CHARACTER:
return -num_decode(s[1:])
n = 0
for c in s:
n = n * BASE + ALPHABET_REVERSE[c]
return n
if __name__ == "__main__":
print num_encode(6147949342)
print num_decode('ILoveYou')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment