At 04:20 PM 8/12/2007, Robert Dailey wrote:
Well, I decided to implement my own way of doing this. I've attached the source. You're all welcome :)

On 8/12/07, Michael Bentley < [EMAIL PROTECTED]> wrote:
Hi Robert,

On Aug 11, 2007, at 3:59 PM, Robert Dailey wrote:
Hi, I was wondering if there is a built in module that supports conversion in any direction between Binary, Hex, and Decimal strings? Thanks.

Shouldn't be too hard to build one.  Here's a little incantation to convert from base 10 to another base:

import string

def to_base(number, base):
'converts base 10 integer to another base'

number = int(number)
base = int(base)
if base < 2 or base > 36:
raise ValueError, "Base must be between 2 and 36"
if not number:
return 0
symbols = string.digits + string.lowercase[:26]
answer = []
while number:
number, remainder = divmod(number, base)
answer.append(symbols[remainder])
return ''.join(reversed(answer))

I've tried to figure out the correct indentation for this, and came up with

========================================
import string

def to_base(n, base):
    'converts base 10 integer to another base, up thru base 36'
    n = int(n)
    base = int(base)
    if base < 2 or base > 36:
        raise ValueError, "Base must be between 2 and 36"
    if not n:
        return 0
    symbols = string.digits + string.lowercase[:26]
    answer = []
    while n:
        n, remainder = divmod(n, base)
        answer.append(symbols[remainder])
    return ''.join(reversed(answer))
n = 12
base = 36
print to_base(n, base)
==========================================
This seems to work fine for n >= base, but not for n < base. For example, the code shown returns "c". Is my indentation wrong, or the code? It seems to me that the code should work for the general case, not just for n >= base.

Dick Moores

How 'bout you hack a from_base function and email it back to me? (hint: type 'help(int)' in the python interpreter).

Peace,
Michael

---
Let the wookie win.




Content-Type: text/plain; name="baseconv.py"
Content-Disposition: attachment; filename="baseconv.py"
X-Attachment-Id: f_f5a5roa4


--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to