Skip to content

Instantly share code, notes, and snippets.

@marcg1968
Created August 31, 2015 09:37
Show Gist options
  • Save marcg1968/5886274913bac202a192 to your computer and use it in GitHub Desktop.
Save marcg1968/5886274913bac202a192 to your computer and use it in GitHub Desktop.
Python convert (encode/decode) base 36
#!/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')
@ctrlcctrlv
Copy link

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.

@singhdan2002
Copy link

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