Created
August 31, 2015 09:37
-
-
Save marcg1968/5886274913bac202a192 to your computer and use it in GitHub Desktop.
Python convert (encode/decode) base 36
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# http://stackoverflow.com/a/1181922 | |
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): | |
"""Converts an integer to a base36 string.""" | |
if not isinstance(number, (int, long)): | |
raise TypeError('number must be an integer') | |
base36 = '' | |
sign = '' | |
if number < 0: | |
sign = '-' | |
number = -number | |
if 0 <= number < len(alphabet): | |
return sign + alphabet[number] | |
while number != 0: | |
number, i = divmod(number, len(alphabet)) | |
base36 = alphabet[i] + base36 | |
return sign + base36 | |
def base36decode(number): | |
return int(number, 36) | |
print base36encode(1412823931503067241) | |
print base36decode('AQF8AA0006EH') |
any idea how this code could be modified to work with floats aswell?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The encoding function allows the user to specify an alphabet, while the decoding function does not, therefore the decoding function is not a true inverse of the encoding function as it relies on the default alphabet.