Hex to Decimal Python Program

Here’s a clip of code to convert either a hex to decimal value, or decimal to hex.

copied from here:


Just modify it for your needs, and it’ll help with sending the commands from the Robosapien arduino library.

# 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 "hex(255) =", hex(255) # 0xff
print "hex2dec('0xff') =", hex2dec('0xff') # 255


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: