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: Decimal to Binary Conversion (Python) (http://www.daniweb.com/forums/thread216539.html)

vegaseat Jun 10th, 2005 2:52 am
Decimal to Binary Conversion (Python)
 
Converting a decimal integer (denary, base 10) to a binary string (base 2) is amazingly simple. An exception is raised for negative numbers and zero is a special case. To test the result, the binary string is converted back to the decimal value, easily done with the int(bStr, 2) function.

  1. # convert a decimal (denary, base 10) integer to a binary string (base 2)
  2. # tested with Python24 vegaseat 6/1/2005
  3.  
  4. def Denary2Binary(n):
  5. '''convert denary integer n to binary string bStr'''
  6. bStr = ''
  7. if n < 0: raise ValueError, "must be a positive integer"
  8. if n == 0: return '0'
  9. while n > 0:
  10. bStr = str(n % 2) + bStr
  11. n = n >> 1
  12. return bStr
  13.  
  14. def int2bin(n, count=24):
  15. """returns the binary of integer n, using count number of digits"""
  16. return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
  17.  
  18. # this test runs when used as a standalone program, but not as an imported module
  19. # let's say you save this module as den2bin.py and use it in another program
  20. # when you import den2bin the __name__ namespace would now be den2bin and the
  21. # test would be ignored
  22. if __name__ == '__main__':
  23. print Denary2Binary(255) # 11111111
  24.  
  25. # convert back to test it
  26. print int(Denary2Binary(255), 2) # 255
  27.  
  28. print
  29.  
  30. # this version formats the binary
  31. print int2bin(255, 12) # 000011111111
  32. # test it
  33. print int("000011111111", 2) # 255
  34.  
  35. print
  36.  
  37. # check the exceptions
  38. print Denary2Binary(0)
  39. print Denary2Binary(-5) # should give a ValueError
vegaseat Sep 17th, 2005 4:01 am
Added an explanation for testing with
if __name__ == '__main__':

Gribouillis Oct 21st, 2009 6:31 am
See also this other snippet


All times are GMT -4. The time now is 2:43 am.

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