Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python base 36 encoding

Tags:

python

How can I encode an integer with base 36 in Python and then decode it again?

like image 433
mistero Avatar asked Jul 25 '09 11:07

mistero


4 Answers

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')
like image 152
kanngard Avatar answered Nov 01 '22 02:11

kanngard


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)
like image 23
mistero Avatar answered Nov 01 '22 00:11

mistero


from numpy import base_repr

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

Here is information about numpy.base_repr.

like image 34
Christopher Beland Avatar answered Nov 01 '22 01:11

Christopher Beland


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

like image 26
André C. Andersen Avatar answered Nov 01 '22 00:11

André C. Andersen