base converter

Greg Jorgensen gregj at pobox.com
Thu Jun 14 04:32:38 EDT 2001


"Fredrik Lundh" <fredrik at pythonware.com> wrote:

> def BaseConvert(x, b):
>     out = ""
>     while x:
>         x, d = divmod(x, b)
>         out = str(d) + out
>     return out
>

Slightly modified to work with bases > 10:

def BaseConvert(x, b):
    "convert decimal number x to base b"
    digits = "0123456789ABCDEF"
    out = ""
    if b <= len(digits):
        while x:
            x, d = divmod(x, b)
            out = digits[d] + out

    return out

Greg Jorgensen
PDXperts LLC
Portland, Oregon USA
gregj at pdxperts.com






More information about the Python-list mailing list