Decimal to Binary Conversion (Python)

vegaseat vegaseat is offline Offline Jun 10th, 2005, 2:52 am |
0
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.
Quick reply to this message  
Python Syntax
  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
0
vegaseat vegaseat is offline Offline | Sep 17th, 2005
Added an explanation for testing with
if __name__ == '__main__':
 
0
Gribouillis Gribouillis is online now Online | 17 Days Ago
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC