944,015 Members | Top Members by Rank

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

Decimal to Binary Conversion (Python)

by on Jun 10th, 2005
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.
Python Code Snippet (Toggle Plain Text)
  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
Comments on this Code Snippet
Sep 17th, 2005
0

Re: Decimal to Binary Conversion (Python)

Added an explanation for testing with
if __name__ == '__main__':
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 21st, 2009
0

Re: Decimal to Binary Conversion (Python)

Posting Maven
Gribouillis is offline Offline
2,655 posts
since Jul 2008
Feb 16th, 2010
0

Re: Decimal to Binary Conversion (Python)

Well...if you are a newbie (like me), here is another solution, although not the best (A better way is certainly the first one on this page).( indentation lost after pasting it here. indent appropriately for the code to work)

#!/usr/bin/env python
import dectobin #Module...defined later
import string #Module.....defined later
a=int(raw_input("Enter a decimal number: "))
if a<0:
print "Try entering a positive number/0 "
elif a==0:
print "Binary: 0"
else:
list=dectobin.conv(a)
list1=string.format(list)
print "Binary: " ,list1

#!/usr/bin/env python
#This function takes an integer as arguement and returns binary equivalent as a list
def conv(a):
bin=[] #Define an empty list which will hold binary values
while(a!=1): #You want to keep dividing your integer with 2 until the quotient becomes 1
b=a%2 #Ccollect remainder.....it will be either 0 or 1
bin.append(b) # Hold this value in the empty list defined earlier
a=a/2

bin.append(1) #The last 1 which will remain after successive division
return bin
#!/usr/bin/env python
def format(list):
j=" " # Define an empty string
for i in range(0,len(list)): # list will have the binary values separated by comma
s=repr(list[i]) #Change each integer to string
j=j+s #Add it to an empty string
j=j[::-1] #Reverse the string
return j
Last edited by armored saint; Feb 16th, 2010 at 10:06 am. Reason: Formatting lost while copying
Newbie Poster
armored saint is offline Offline
1 posts
since Feb 2010
Feb 17th, 2010
0

Re: Decimal to Binary Conversion (Python)

There are 1000 ways to do this, and you just added way #1001
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Feb 17th, 2010
0

Re: Decimal to Binary Conversion (Python)

Here's a simple version using the bin() builtin while giving the same formatting options as the original example. Everyone has their own version of this, yet I still have yet to find a place where a string of the binary version of a number is useful.

Python Syntax (Toggle Plain Text)
  1. def binary(n, digits=8):
  2. rep = bin(n)[2:]
  3. return ('0' * (digits - len(rep))) + rep
Newbie Poster
GothAlice is offline Offline
1 posts
since Feb 2010
Feb 17th, 2010
0

Re: Decimal to Binary Conversion (Python)

About the formatting in the previous example, you can also use the format operator
python Syntax (Toggle Plain Text)
  1. def binary(n, digits=8):
  2. return "{0:0>{1}}".format(bin(n)[2:], digits)
See this snippet about the marvels of format().
Last edited by Gribouillis; Feb 17th, 2010 at 3:14 pm.
Posting Maven
Gribouillis is offline Offline
2,655 posts
since Jul 2008
Feb 17th, 2010
0

Re: Decimal to Binary Conversion (Python)

Lambda always intrigues me:
Python Syntax (Toggle Plain Text)
  1. # works with IronPython, Python2 and Python3
  2.  
  3. d = 255
  4. # a recursive dec to bin function
  5. d2b = lambda d: (not isinstance(d,int) or (d==0)) and '0' \
  6. or (d2b(d//2)+str(d%2))
  7.  
  8. print(d2b(d)) # 011111111
Posting Virtuoso
Lardmeister is offline Offline
1,701 posts
since Mar 2007
Aug 14th, 2011
0

Utility of string of binary version of number.

@ vegaseat: Thank you. Are you also vegasclimb?

@GothAlice:

"where string of the binary version is useful"?
For generating 1D fractals: http://tatetech.blogspot.com/2011/08/generating-1d-quasi-sierpinski-fractal.html
Python Syntax (Toggle Plain Text)
  1. #!/usr/bin/python
  2.  
  3.  
  4. """ make1DFractalBin.py
  5.  
  6. arg1 = Natural(for order of fractal)
  7.  
  8. arg2 = Natural(in 512 -- 527, 576 -- 591, 640 -- 655, 704 --719,
  9.  
  10. 768 -- 783, 832 -- 847, 896 -- 911, 960 -- 975) for mask)
  11.  
  12. Generates a 1D fractal of order N,
  13.  
  14. where the fractal generated by 975 is
  15.  
  16. 1. removing the middle third of each segment
  17.  
  18. 2. stretching by 3
  19.  
  20. equivalent to more complicated make1DFractal.py Natural
  21.  
  22. """
  23.  
  24.  
  25. import sys
  26.  
  27. # convert a decimal integer to a binary string (base 2)
  28.  
  29. # tested with Python24 vegaseat 6/1/2005
  30.  
  31. #
  32.  
  33. def Denary2Binary(n):
  34.  
  35. """convert denary integer n to binary string bStr"""
  36.  
  37. bStr = ''
  38.  
  39. if n < 0: raise ValueError, "must be a positive integer"
  40.  
  41. if n == 0: return '0'
  42.  
  43. while n > 0:
  44.  
  45. bStr = str(n % 2) + bStr
  46.  
  47. n = n >> 1
  48.  
  49. return bStr
  50.  
  51. #
  52.  
  53. def main():
  54.  
  55. maskDec = 975 # generator for Sierpinski square
  56.  
  57. #Read commandline argument for order of fractal
  58.  
  59. if len(sys.argv) < 2:
  60.  
  61. print "usage: $ python make1DFractalBin.py Natural(Order of fractal) [Natur\
  62.  
  63. al](default = 975, else see top of file for allowed generators)"
  64.  
  65. sys.exit(2)
  66.  
  67. else:
  68.  
  69. order = int(sys.argv[1])
  70.  
  71. print "Order of Fractal ordered: ", order, '\n'
  72.  
  73. if len(sys.argv) ==3:
  74.  
  75. maskDec = int(sys.argv[2])
  76.  
  77.  
  78. print "Generator = ", maskDec
  79.  
  80. maskB = Denary2Binary(maskDec)
  81.  
  82. print "Mask = \n",maskB
  83.  
  84.  
  85. iter = 0
  86.  
  87. while iter < order:
  88.  
  89. l = len(maskB)-1
  90.  
  91. """ multiply the mask by 2**(twice its binary length), and add its original value. This is equivalent to stretching it and removing middle third.
  92.  
  93. """
  94.  
  95. maskDec = maskDec*((3-1)**(2*l)) + maskDec
  96.  
  97. maskB = Denary2Binary(maskDec)
  98.  
  99. print maskB
  100.  
  101. iter+=1
  102.  
  103.  
  104. if __name__ == '__main__':
  105.  
  106. main()

For order 2 and generator 975 we get:

rtate-mn:paths rtate$ python make1DFractalBin.py 2 975

Order of Fractal ordered: 2


Generator = 975

Mask =

1111001111

1111001111000000001111001111

1111001111000000001111001111000000000000000000000000001111001111000000001111001111

Now all I have to do is "square it"!
Newbie Poster
tatetech is offline Offline
1 posts
since Aug 2011
Nov 15th, 2011
0

Re: Decimal to Binary Conversion (Python)

A rather straightforward one-liner to do the same thing:

python Syntax (Toggle Plain Text)
  1. >>> bin(10)[2:].rjust(8, '0')
  2. '00001010'
Newbie Poster
whitelynx is offline Offline
1 posts
since Nov 2011
Message:
Previous Thread in Python Forum Timeline: help understanding this code
Next Thread in Python Forum Timeline: Post-process generated values with a decorator.





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


Follow us on Twitter


© 2011 DaniWeb® LLC