base converter

Fredrik Lundh fredrik at pythonware.com
Thu Jun 14 06:15:21 EDT 2001


Greg Jorgensen wrote:
> 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

slightly modified to work with bases up to 36 (or more),
and return "0" for zero:

import string

def BaseConvert(x, b, digits=string.digits+string.uppercase):
    "convert decimal number x to base b"
    assert b < len(digits)
    out = ""
    while x:
        x, d = divmod(x, b)
        out = digits[d] + out
    return out or "0"

(still waiting for someone to come up with a one-liner using
list comprehensions ;-)

</F>





More information about the Python-list mailing list