Python Convert Decimal to 62 Base: A Completed Guide – Python Tutorial

By | December 14, 2019

Nowadays, shortening a long url to a short one is widely used. The basic algorithm behind this is to convert a decimal number to 62 base. In this tutorial, we will discuss how to convert in python.

What is 62 base?

It is consisted of 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.

For example: Z = 61 and 10 = 62

How to convert a decimal to 62 base?

We will write an example to show you how to convert.

BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def encode(num, alphabet=BASE62):
    if num == 0:
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        num, rem = divmod(num, base)
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)

In this example, we will use encode() function to convert a decimal to 62 base.

Here is example:

print(encode(10))
print(encode(62))
print(encode(100))
print(encode(100000))

The 62 base numbers are:

a
10
1C
q0U

How to convert a 62 base to decimal?

We also can create a function to convert.

def decode(string, alphabet=BASE62):
    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

We can use this function like:

print(decode('a'))
print(decode('10'))
print(decode('1C'))
print(decode('q0U'))

The decimal numbers are:

10
62
100
100000

Leave a Reply