944,068 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 3822
  • Python RSS
0

Binary-to-Decimal and vice-versa

by on Oct 20th, 2009
Simple functions for binary-to-decimal and decimal-to-binary conversion
Python Code Snippet (Toggle Plain Text)
  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 )
Comments on this Code Snippet
Oct 20th, 2009
0

Re: Binary-to-Decimal and vice-versa

Also note
python Syntax (Toggle Plain Text)
  1. >>> bin(45) # python >= 3.0
  2. '0b101101'
  3. >>> int('1110', 2) # python >= 2.5
  4. 14
Finally, see also this link.
Posting Maven
Gribouillis is offline Offline
2,656 posts
since Jul 2008
Oct 20th, 2009
0

Re: Binary-to-Decimal and vice-versa

Python Syntax (Toggle Plain Text)
  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.
Posting Whiz in Training
masterofpuppets is offline Offline
272 posts
since Jul 2009
Oct 20th, 2009
1

Re: Binary-to-Decimal and vice-versa

If you are curious, also check this out:
http://www.daniweb.com/code/snippet216539.html
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Jun 17th, 2010
0

working nice......

thanx man..
Newbie Poster
b_nayok is offline Offline
1 posts
since Jun 2010
Jun 17th, 2010
0

Re: Binary-to-Decimal and vice-versa

Then there is connected discussion aboult long binary numbers for your information in this thread (link directly to my solution)
http://www.daniweb.com/forums/post12...ml#post1219556
Industrious Poster
pyTony is offline Offline
4,208 posts
since Apr 2010
Message:
Previous Thread in Python Forum Timeline: Getting information from web page with Python
Next Thread in Python Forum Timeline: How would you create a sub-menu for python code?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC