[Tutor] RE: Base converter bases 2-62
Magnus Lyckå
magnus@thinkware.se
Thu Jun 19 20:02:02 2003
At 23:23 2003-06-19 +0000, cino hilliard wrote:
>I have created a base converter in python to take advantage of the
>arbitrary integer precision and
>provide an alternative to the one way function of int(s,[radix]) and
>long(s,[radix]).
I don't really see a reason to duplicate int or long.
Use them if they work! (How often do you need a base
higher than 36? :)
If you want to implement their inverse, i.e. going from a
numeric value to a representation in a given base, it's
much easier if you use a string instead of all that if-stuff.
If you want to go from one string representation to another
it's simple to combine these two functions. I don't see any
gain in implementing both in a single function. (Well, for
fun is a good reason I guess. :)
We can do something like this:
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def numToBase(num, base):
stack = []
while num:
stack.append(digits[num % base])
num = num // base
stack.reverse()
return "".join(stack)
This version only work for positive numbers though.
But it's fairly simple to handle negatives and zero
I think. I leave it as an excise to the reader...
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language