Jeff Wagner wrote in message said:
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.