Python base 36 encoding

Have you tried Wikipedia's sample code?

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')

You can use numpy's base_repr(...) for this.

import numpy as np

num = 2017

num = np.base_repr(num, 36)
print(num)  # 1K1

num = int(num, 36)
print(num)  # 2017

Here is some information about numpy, int(x, base=10), and np.base_repr(number, base=2, padding=0).

(This answer was originally submitted as an edit to @christopher-beland's answer, but was rejected in favor of its own answer.)


I wish I had read this before. Here is the answer:

def base36encode(number):
    if not isinstance(number, (int, long)):
        raise TypeError('number must be an integer')
    is_negative = number < 0
    number = abs(number)

    alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '']

    while number:
        number, i = divmod(number, 36)
        base36 = alphabet[i] + base36
    if is_negative:
        base36 = '-' + base36

    return base36 or alphabet[0]


def base36decode(number):
    return int(number, 36)

print(base36encode(1412823931503067241))
print(base36decode('AQF8AA0006EH'))
assert(base36decode(base36encode(-9223372036721928027)) == -9223372036721928027)

from numpy import base_repr

num = base_repr(num, 36)
num = int(num, 36)

Here is information about numpy.base_repr.

Tags:

Python