sometimes a cigar is just a cigar
Header image

python hex to dec and dec to hex converter

Posted by ALonon in Python

# change a hexadecimal string to decimal number and reverse
# check two different representations of the hexadecimal string
# negative values and zero are accepted
# tested with Python24        vegaseat     11oct2005

def dec2hex(n):
“”"return the hexadecimal string representation of integer n”"”
return “%X” % n

def hex2dec(s):
“”"return the integer value of a hexadecimal string s”"”
return int(s, 16)

print “dec2hex(255)  =”, dec2hex(255)    # FF
print “hex2dec(‘FF’) =”, hex2dec(‘FF’)   # 255

print

print “hex(255) =”, hex(255)                # 0xff
print “hex2dec(’0xff’) =”, hex2dec(’0xff’)  # 255

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>