Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Created February 7, 2020 05:13
Show Gist options
  • Save RussellLuo/267a1c86d4ef382960e38e6fc366d495 to your computer and use it in GitHub Desktop.
Save RussellLuo/267a1c86d4ef382960e38e6fc366d495 to your computer and use it in GitHub Desktop.
An encoder that can encode a decimal number to a string in any base, and vice versa.
class BaseEncoder:
"""
An encoder that can encode a decimal number to a string in any base, and vice versa.
Example usage:
>>> import string
>>> chars_62 = string.digits + string.ascii_letters[:52]
>>> encoder = BaseEncoder(chars_62)
>>> encoder.encode(10765432100123456789)
'cPfNbbhTpel'
>>> encoder.decode('cPfNbbhTpel')
10765432100123456789L
"""
def __init__(self, chars):
self.__chars = chars
self.__indices = {c: i for i, c in enumerate(chars)}
self.__base_size = len(chars)
def encode(self, n):
encoded = []
while n > 0:
n, r = divmod(n, self.__base_size)
encoded.append(self.__chars[r])
return ''.join(encoded[::-1])
def decode(self, s):
n = 0L
for c in s:
n = n * self.__base_size + self.__indices[c]
return n
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment