Base conversion method or module

Francis Avila francisgavila at yahoo.com
Sun Dec 7 15:45:41 EST 2003


Jeff Wagner wrote in message <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc at 4ax.com>...
>Is there a Python module or method that can convert between numeric bases?
Specifically, I need to
>convert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b.
>
>I searched many places but couldn't find a Python specific one.
>
>Thanks, Jeff

There was a Python cookbook recipe that did these kinds of conversions,
IIRC.  Look around at http://aspn.activestate.com/ASPN/Cookbook/Python.
Numeric might do this sort of thing, too, but I don't know.

Python itself can get you pretty far; the problem is that it's a bit spotty
in making conversions communicable.

For example, int() and long() both accept a string with a base argument, so
you can convert just about any base (2 <= base <= 36) to a Python int or
long.

Python can also go the other way around, taking a number and converting to a
string representation of the bases you want.  The problem? There's only a
function to do this for hex and oct, not for bin or any of the other bases
int can handle.

Ideally, there's be a do-it-all function that is the inverse of int(): take
a number and spit out a string representation in any base (2-36) you want.

But the binary case is pretty simple:

def bin(number):
    """bin(number) -> string

    Return the binary representation of an integer or long integer.

    """
    if number == 0: return '0b0'
    binrep = []
    while number >0:
        binrep.append(number&1)
        number >>= 1
    binrep.reverse()
    return '0b'+''.join(map(str,binrep))


Dealing with negative ints is an exercise for the reader....

Remember also that Python has hex and octal literals.
--
Francis Avila





More information about the Python-list mailing list