RSS Forums RSS
Please support our Python advertiser: Programming Forums

Starting Python

Join Date: Oct 2004
Posts: 2,576
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 11
Solved Threads: 184
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

  #28  
Sep 10th, 2005
The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...
  1. # two different ways to represent integer 705083 as a hexadecimal number
  2. # 0x is the official prefix for a hexnumber
  3. # the results appear different, but both are of type string and change back to base 10 properly
  4.  
  5. # using the hex() function
  6. hex1 = hex(705083)
  7. print hex1, type(hex1), int(hex1,16) # result = 0xac23b <type 'str'> 705083
  8.  
  9. # using the format operator %
  10. hex2 = "%X" % 705083
  11. print hex2, type(hex2), int(hex2, 16) # result = AC23B <type 'str'> 705083
  12.  
  13. # let's time the two options ...
  14.  
  15. import timeit
  16.  
  17. t = timeit.Timer('hex(705083)')
  18. elapsed = (10 * t.timeit(number=100000))
  19. print 'Function hex(705083) takes %0.3f micro-seconds/pass' % elapsed
  20.  
  21. t = timeit.Timer('"%X" % 705083')
  22. elapsed = (10 * t.timeit(number=100000))
  23. print 'The format operator takes %0.3f micro-seconds/pass' % elapsed
Last edited by vegaseat : Mar 1st, 2007 at 3:47 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 3:31 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC