# [Tutor] Doing this in reverse?

Marc Tompkins marc.tompkins at gmail.com
Sun Sep 14 09:08:52 CEST 2008

```On Sat, Sep 13, 2008 at 6:02 PM, Alan Gilfoy <agilfoy at frontiernet.net>wrote:

> 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:
>

The built-in int() function does what you need - give it a string
representation of a number in any base 2-36; pass the base as the second
argument.  The return is an integer - a pure, Platonic integer - which you
can then print in any base you choose.
If you omit the second argument (as you usually do), the base is assumed to
be 10.
The documentation says that if you pass 0 as the second argument, Python
will try to guess the base, but it didn't work when I tried it.

Example:
>> int('FF', 16)
255

Now, about the code you posted -
When you perform integer division, you basically go back to second-grade
math (you know, before you learned long division...)
The "/" operator returns the integer quotient - example:
>> 7 / 2
3

The "%" operator - aka "modulo" - returns the remainder - example:
>> 7 % 2
1

So...
s = ""
while 1: # keep looping until we break out explicitly
r = n % base # divide n by base, r is the remainder
s = digits[r] + s  # look up which digit r corresponds to, add it to
the left side of the string we're building
n = n / base  # divide n by base again, this time keeping only the
integer quotient
if n == 0:  #  if quotient is 0,
break   # we're done

--
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080914/b22bdd9a/attachment.htm>
```