Binary-to-Decimal and vice-versa

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
masterofpuppets masterofpuppets is offline Offline Oct 20th, 2009, 11:34 am |
0
Simple functions for binary-to-decimal and decimal-to-binary conversion
Quick reply to this message  
Python Syntax
  1. # Simple functions to convert from decimal to binary and vice-versa
  2.  
  3. def toBinary( decimalNumber ):
  4. quotient = 1
  5. remainder = 0
  6. tmpNum = decimalNumber
  7. finalNumberList = []
  8. n = ""
  9.  
  10. #e.g. take 14...
  11. while quotient != 0:
  12. remainder = decimalNumber % 2 #14 % 2 = 0
  13. quotient = decimalNumber / 2 #14 / 2 = 7
  14. decimalNumber = quotient # 7 % 2 = 1 and so on...
  15. finalNumberList.insert( 0, remainder )
  16.  
  17. # Used because all numbers are in a list, i.e. convert to string
  18. for num in finalNumberList:
  19. n += str( num )
  20. return n
  21.  
  22. def toDecimal( binaryNumber ):
  23. multiplier = 0
  24. number = 0
  25. for el in binaryNumber[ : : -1 ]:
  26. number += int( el ) * ( 2**multiplier )
  27. multiplier += 1
  28. return number
  29.  
  30. print toDecimal( "1110" )
  31. print toBinary( 45 )
0
Gribouillis Gribouillis is online now Online | Oct 20th, 2009
Also note
  1. >>> bin(45) # python >= 3.0
  2. '0b101101'
  3. >>> int('1110', 2) # python >= 2.5
  4. 14
Finally, see also this link.
 
0
masterofpuppets masterofpuppets is offline Offline | Oct 20th, 2009
  1. >>> int('1110', 2) # python >= 2.5
  2. 14

hahh thanks for that bro. I've actually never tried it before and didn't know it existed.....weird
Last edited by masterofpuppets; Oct 20th, 2009 at 12:29 pm.
 
0
bumsfeld bumsfeld is offline Offline | Oct 20th, 2009
If you are curious, also check this out:
http://www.daniweb.com/code/snippet216539.html
 
 

Message:


Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC