python allows conversions from string to integer using any base in the range [2,36] using:
int(string,base)
im looking for an elegant inver
The above answers are really nice. It helped me a lot to prototype an algortithm I had to implement in C
I'd like to come up with a little change (I used) to convert decimal to a base of symbolspace
I also ignored negativ values just for shortness and the fact that's mathematical incorrect --> other rules for modular arithmetics --> other math if you use binary, oct or hex --> diff in unsigned & signed values
def str_base(number, base):
(d,m) = divmod(number,len(base))
if d > 0:
return str_base(d,base)+base[m]
return base[m]
that lead's to following output
>>> str_base(13,'01')
'1101'
>>> str_base(255,'01')
'11111111'
>>> str_base(255,'01234567')
'377'
>>> str_base(255,'0123456789')
'255'
>>> str_base(255,'0123456789abcdef')
'ff'
>>> str_base(1399871903,'_helowrd')
'hello_world'
if you want to padd with the propper zero symbol you can use
symbol_space = 'abcdest'
>>> str_base(734,symbol_space).rjust(0,symbol_space[0])
'catt'
>>> str_base(734,symbol_space).rjust(6,symbol_space[0])
'aacatt'