Well, I decided to implement my own way of doing this. I've attached the
source. You're all welcome :)
On 8/12/07, Michael Bentley <[EMAIL PROTECTED]> wrote:
>
> Hi Robert,
> On Aug 11, 2007, at 3:59 PM, Robert Dailey wrote:
>
> Hi, I was wondering if there is a built in module that supports conversion
> in any direction between Binary, Hex, and Decimal strings? Thanks.
>
>
> Shouldn't be too hard to build one. Here's a little incantation to
> convert from base 10 to another base:
>
> import string
>
> def to_base(number, base):
> 'converts base 10 integer to another base'
>
> number = int(number)
> base = int(base)
> if base < 2 or base > 36:
> raise ValueError, "Base must be between 2 and 36"
> if not number:
> return 0
> symbols = string.digits + string.lowercase[:26]
> answer = []
> while number:
> number, remainder = divmod(number, base)
> answer.append(symbols[remainder])
> return ''.join(reversed(answer))
>
> How 'bout you hack a from_base function and email it back to me? (hint:
> type 'help(int)' in the python interpreter).
>
> Peace,
> Michael
>
> ---
> Let the wookie win.
>
>
>
>
###############################################################################
def hex2dec( hex ):
return str( int( hex, 16 ) )
###############################################################################
def hex2bin( hex ):
nibbles = {
"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "A":"1010", "B":"1011",
"C":"1100", "D":"1101", "E":"1110", "F":"1111"
}
# Check for '0x' in front of the string & remove it
if hex[:2] == "0x":
hex = hex[2:]
try:
return str().join([nibbles[c] for c in hex.upper()]).lstrip("0")
except KeyError:
print "ERROR --> Non-hexadecimal character specified."
###############################################################################
def dec2hex( dec ):
result = hex( int( dec ) )
return result[:2] + result[2:].upper()
###############################################################################
def dec2bin( dec ):
return hex2bin( dec2hex( dec ) )
###############################################################################
def bin2dec( bin ):
return str( int( bin, 2 ) )
###############################################################################
def bin2hex( bin ):
return dec2hex( bin2dec( bin ) )
###############################################################################
--
http://mail.python.org/mailman/listinfo/python-list