Skip to content

Instantly share code, notes, and snippets.

@ahknight
Created August 21, 2014 13:56
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 ahknight/8797872af6d4245ca6ff to your computer and use it in GitHub Desktop.
Save ahknight/8797872af6d4245ca6ff to your computer and use it in GitHub Desktop.
Simple base converter for Py
#!/usr/bin/env python3
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(n):
result = ""
while (n > 0):
n,m = divmod(n,len(ALPHABET))
result = ALPHABET[m] + result
return result
def decode(encoded):
result = 0
for i in range(len(encoded)):
value = ALPHABET.index(encoded[i])
result += value * (len(ALPHABET) ** (len(encoded) - i - 1))
return result
n = 4503599627371331
print("IN: %d" % n)
enc = encode(n)
print("ENC: %s" % enc)
dec = decode(enc)
print("OUT: %d" % dec)
@ahknight
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment