DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Code Snippet: Hexadecimal to Decimal (Python) (http://www.daniweb.com/forums/thread216638.html)

vegaseat Oct 12th, 2005 2:19 am
Hexadecimal to Decimal (Python)
 
This snippet explores the change of a hexadecimal (base 16) string to a denary (base 10) integer and the reverse. Interestingly Python allows the representation of the hexadecimal string in two different forms. For instance 255 can be changed to 'FF' (also 'ff') or '0xff'. Any of these hexadecimal strings return the correct value of 255 again.

  1. # change a hexadecimal string to decimal number and reverse
  2. # check two different representations of the hexadecimal string
  3. # negative values and zero are accepted
  4. # tested with Python24 vegaseat 11oct2005
  5.  
  6. def dec2hex(n):
  7. """return the hexadecimal string representation of integer n"""
  8. return "%X" % n
  9.  
  10. def hex2dec(s):
  11. """return the integer value of a hexadecimal string s"""
  12. return int(s, 16)
  13.  
  14. print "dec2hex(255) =", dec2hex(255) # FF
  15. print "hex2dec('FF') =", hex2dec('FF') # 255
  16.  
  17. print
  18.  
  19. print "hex(255) =", hex(255) # 0xff
  20. print "hex2dec('0xff') =", hex2dec('0xff') # 255

All times are GMT -4. The time now is 6:45 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC