[Tutor] Doing this in reverse?
agilfoy at frontiernet.net
Sun Sep 14 03:02:43 CEST 2008
I found a script at http://code.activestate.com/recipes/65212/ that
allows you to convert base 10 numbers to another base. I would like to
convert non-base10 numbers to base 10. I wonder if I can do so by
flipping the script around a bit:
# (Lovingly) ripped off from a reply to the post at
# The function code is from that page
# User Interface + comments created by Alan Gilfoy, 2007-2008
def baseconvert(n, base):
"""convert positive decimal integer n to equivalent in another
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# a thru z only apply in base 11 and up.
# base 11 uses only a, base 12 uses a thru b, base 13 uses a thru
c, and so on.
# 'a' is equivalent to '10' in decimal, 'b' is equivalent to '11', etc.
n = int(n)
base = int(base)
if n < 0 or base < 2 or base > 36:
s = ""
r = n % base
s = digits[r] + s
n = n / base
if n == 0:
I'm not entirely sure how this works; I just know that it does.
It looks like the program goes through a loop that "chops away" at the
inputted number, gradually adding to the outputted number as
And what exactly does the % operator mean?
More information about the Tutor