On Sat, Sep 13, 2008 at 6:02 PM, Alan Gilfoy <[EMAIL PROTECTED]>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
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor