"""Convert numbers from base 10 integers to base X strings and back again.Sample usage:>>> base20 = BaseConverter('0123456789abcdefghij')>>> base20.from_decimal(1234)'31e'>>> base20.to_decimal('31e')1234"""classBaseConverter(object):decimal_digits="0123456789"def__init__(self,digits):self.digits=digitsdeffrom_decimal(self,i):returnself.convert(i,self.decimal_digits,self.digits)defto_decimal(self,s):returnint(self.convert(s,self.digits,self.decimal_digits))defconvert(number,fromdigits,todigits):# Based on http://code.activestate.com/recipes/111286/ifstr(number)[0]=='-':number=str(number)[1:]neg=1else:neg=0# make an integer out of the numberx=0fordigitinstr(number):x=x*len(fromdigits)+fromdigits.index(digit)# create the result in base 'len(todigits)'ifx==0:res=todigits[0]else:res=""whilex>0:digit=x%len(todigits)res=todigits[digit]+resx=int(x/len(todigits))ifneg:res='-'+resreturnresconvert=staticmethod(convert)bin=BaseConverter('01')hexconv=BaseConverter('0123456789ABCDEF')base62=BaseConverter('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz')if__name__=='__main__':nums=[-10**10,10**10]+range(-100,100)forconvertorin[bin,hexconv,base62]:foriinnums:asserti==bin.to_decimal(bin.from_decimal(i)),'%s failed'%i