Skip to content

Instantly share code, notes, and snippets.

@kljensen
Created October 5, 2010 17:09
Show Gist options
  • Save kljensen/611915 to your computer and use it in GitHub Desktop.
Save kljensen/611915 to your computer and use it in GitHub Desktop.
class HighBaseEncoder(object):
"""docstring for HighBaseEncoder
http://stackoverflow.com/questions/1119722/base-62-conversion-in-python
"""
def __init__(self):
super(HighBaseEncoder, self).__init__()
ALPHABET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
@classmethod
def encode(cls, num, alphabet=None):
"""Encode a number in Base X
`num`: The number to encode
`alphabet`: The alphabet to use for encoding
"""
if not alphabet:
alphabet = cls.ALPHABET
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
@classmethod
def decode(cls, string, alphabet=None):
"""Decode a Base X encoded string into the number
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
"""
if not alphabet:
alphabet = cls.ALPHABET
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
return num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment