Arbitrary Base Number Converter


In [here], the base 62 number conversion to base 10 is implemented. To extend the conversion to arbitrary bases, we can use base 10 as the intermediate base, i.e. we first convert the base to base 10 and then further convert to base b.

As you will see, the implementation is quite similar, we can put it in a single function.

#!/usr/bin/env python
# convert.py
# https://helloacm.com
# https://rot47.net
# Arbitrary Base Number Converter

from math import floor

BASE2  = "01";
BASE8  = "01234567";
BASE10 = "0123456789";
BASE16 = "0123456789abcdef";
BASE32 = "0123456789abcdefghijklmnopqrstuvwxyz";
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
BASE75 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.,!=-*(){}[]";

def convert(src, srctable, desttable):
    srclen = len(srctable)
    destlen = len(desttable)
    # first convert to base 10
    val = 0
    numlen = len(src)
    for i in xrange(numlen):
        val = val * srclen + srctable.find(src[i])
    if val < 0:
        return 0
    # then convert to any base
    r = val % destlen
    res = desttable[r];
    q = floor(val / destlen)
    while q:
        r = q % destlen
        q = floor(q / destlen)
        res = desttable[int(r)] + res;
    return res

The page provides the Javascript implementation of the above algorithm, meanwhile, you can mess around with the input/output alphabets e.g. ‘9876543210’ for fun.

Also, in the page, there are other implementation, such as VBScript and Javascript.

The PHP provides the function base_convert which can convert a number between arbitrary bases.

string base_convert ( string $number , int $frombase , int $tobase )

This function returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. However, frombase and tobase have to be set between two and thirty-six, inclusive. The characters in numbers with a base higher than ten will be represented by the alphabetic letters a-z, with a meaning ten, b meaning eleven and z meaning thirty-five.
–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
378 words
Last Post: Base62
Next Post: Codeforces: A. Chat Server's Outgoing Traffic

The Permanent URL is: Arbitrary Base Number Converter

Leave a Reply