Converting Bases In Python

maxbase = 62
baselist = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
def convert_to_decimal(convert, basefrom):
    convert = str(convert)
 
    if basefrom < 2 or basefrom > maxbase or not convert:
        return 0
 
    basefrom = baselist[0:basefrom]
    total = 0
 
    # Time to convert to decimal!
    for i, num in enumerate(convert[::-1]):
        val = basefrom.find(str(num))
        if val == -1: return 0
        total = total + (val * pow(len(basefrom), i))
 
    return total
 
def convert_from_decimal(number, baseto):
    if number < 0 or baseto < 2 or baseto > maxbase:
        return ""
 
    baseto = baselist[0:baseto]
    retstring = ""
 
    # Time to convert from decimal!
    while (number > 0):
        val = baseto[number % len(baseto)]
        retstring = val + retstring
        number = number / len(baseto)
 
    return retstring
 
def convert_base(convert, basefrom, baseto):
    return convert_from_decimal(convert_to_decimal(convert, basefrom), baseto)
 
python/base_converter.txt · Last modified: 2010/02/08 21:53 by TkTech
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki