I'm trying to convert a decimal number to an arbitrary base and back to decimal. I found this code below from another question:
def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
'convert an integer to its string representation in a given base'
if b<2 or b>len(alphabet):
if b==64: # assume base64 rather than raise error
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
else:
raise AssertionError("int2base base out of range")
if isinstance(x,complex): # return a tuple
return ( int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet) )
if x<=0:
if x==0:
return alphabet[0]
else:
return '-' + int2base(-x,b,alphabet)
# else x is non-negative real
rets=''
while x>0:
x,idx = divmod(x,b)
rets = alphabet[idx] + rets
return rets
When I convert a decimal to hex:
in_base16 = int2base(number, 16)
it works, but when I try to convert that result back to decimal (base 10):
back_to_10 = int2base(in_base16, 10)
... it gives me the error:
if x<=0:
TypeError: '<=' not supported between instances of 'str' and 'int'
It can't convert a string back to a number for some reason. I don't understand why. How would I convert a number of an arbitrary base back to decimal?