<html>
<body>
At 04:20 PM 8/12/2007, Robert Dailey wrote:<br>
<blockquote type=cite class=cite cite="">Well, I decided to implement my
own way of doing this. I've attached the source. You're all welcome
:)<br><br>
On 8/12/07, <b>Michael Bentley</b>
<<a href="mailto:michael@jedimindworks.com">
michael@jedimindworks.com</a>> wrote:<br>

<dl>
<dd>Hi Robert,<br><br>

<dd>On Aug 11, 2007, at 3:59 PM, Robert Dailey wrote:<br>
<blockquote type=cite class=cite cite="">
<dd>Hi, I was wondering if there is a built in module that supports
conversion in any direction between Binary, Hex, and Decimal strings?
Thanks. </blockquote><br>

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

<dd>import string<br><br>

<dd>def to_base(number, base):<br>

<dd>'converts base 10 integer to another base'<br><br>

<dd>number = int(number)<br>

<dd>base = int(base)<br>

<dd>if base < 2 or base > 36:<br>

<dd>raise ValueError, "Base must be between 2 and 36" <br>

<dd>if not number:<br>

<dd>return 0<br>

<dd>symbols = string.digits + string.lowercase[:26]<br>

<dd>answer = []<br>

<dd>while number:<br>

<dd>number, remainder = divmod(number, base)<br>

<dd>answer.append(symbols[remainder]) <br>

<dd>return ''.join(reversed(answer))</blockquote>
</dl><br>
I've tried to figure out the correct indentation for this, and came up
with<br><br>
========================================<br>
import string<br><br>
def to_base(n, base):<br>
    'converts base 10 integer to another base, up thru
base 36'<br>
    n = int(n)<br>
    base = int(base) <br>
    if base < 2 or base > 36:<br>
        raise ValueError, "Base
must be between 2 and 36" <br>
    if not n:<br>
        return 0<br>
    symbols = string.digits + string.lowercase[:26] <br>
    answer = []<br>
    while n:<br>
        n, remainder = divmod(n,
base)<br>
       
answer.append(symbols[remainder]) <br>
    return ''.join(reversed(answer))<br>
n = 12<br>
base = 36<br>
print to_base(n, base)<br>
==========================================<br>
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.<br><br>
Dick Moores<br><br>
<blockquote type=cite class=cite cite="">
<dl>
<dd>How 'bout you hack a from_base function and email it back to me?
(hint: type 'help(int)' in the python interpreter).<br><br>

<dd>Peace,<br>

<dd>Michael<br><br>

<dd>---<br>

<dd>Let the wookie win.<br><br>
<br><br>

</dl><br>
Content-Type: text/plain; name="baseconv.py"<br>
Content-Disposition: attachment; filename="baseconv.py"<br>
X-Attachment-Id: f_f5a5roa4<br><br>
<br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" eudora="autourl">
http://mail.python.org/mailman/listinfo/python-list</a></blockquote>
</body>
</html>