Python base converter

Converts from any base less than or equal to 36 to any other base less than or equal to 36. This is my first python program so it is definitely not amazing, but I don’t think I did too bad.

My verdict on python, the interpreter works great for the quick scripts, but dynamic typing drives me crazy. For ex. trying to iterate through all the letters in the input it tries to treat it as an int and complains. Just seems too unpredictable and hard to catch errors. I get a feeling like there are a ton of errors waiting to happen : (

Anyway, here is the code, enjoy : )

'''
Created on Sep 6, 2009                                                

@author: syfran
'''            

def convert(oBase, oNum, newBase):

    if(oBase > 36 or newBase > 36):
        print "Please use a base lower than or equal to 36"
        quit()                                             

    numToLett = {10:"A", 11:"B", 12:"C", 13:"D", 14:"E", 15:"F", 16:"G", 17:"H", 18:"I", 19:"J", 20:"K", 21:"L", 22:"M", 23:"N", 24:"O", 25:"P", 26:"Q", 27:"R", 28:"S", 29:"T", 30:"U", 31:"V", 32:"W", 33:"X", 34:"Y", 35:"Z"}
    # returns a function that is used to quickly calculate a power
    def getToPower(base):
        def toPower(exponent):
            return pow(base, exponent)
        return toPower
    # converts the list into a solid string
    def listToString(list):
        returnString = ""
        for letter in list:
            returnString += str(letter)
        return returnString                                                                                                    

    def replaceAlpha(num):
        for value in numToLett:
            if num.upper() == numToLett[value]:
                return value                   

    def addAlpha(num):
        return numToLett[num]                  

    newNum = []
    oBasePower = getToPower(oBase)
    newBasePower = getToPower(newBase)         

    # first convert to decimal
    deci = 0
    exp = len(oNum) - 1
    for digit in oNum:
        if digit.isalpha():
            digit = replaceAlpha(digit)
        deci += oBasePower(exp) * int(digit)
        exp -= 1                               

    # find the highest possible starting number for the new Base
    exp = 0
    while deci >= newBasePower(exp + 1):
        exp += 1                                                

    # break it down into the divisors
    while exp >= 0:
        coeff = deci / newBasePower(exp)
        deci -= newBasePower(exp) * coeff
        if coeff > 9:
            coeff = addAlpha(coeff)
        newNum.append(coeff);
        exp -= 1

    # return
    return listToString(newNum)

def run():
    num = raw_input("Please enter number")
    originalBase = raw_input("Please enter starting base")
    newBase = raw_input("Please enter new Base")
    print convert(int(originalBase),str(num),int(newBase))

if __name__ == '__main__':
    run()

Leave a Reply