Decimal to Binary Conversion (Python)

vegaseat 1 Tallied Votes 7K Views Share

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.

# convert a decimal (denary, base 10) integer to a binary string (base 2)
# tested with Python24   vegaseat    6/1/2005

def Denary2Binary(n):
    '''convert denary integer n to binary string bStr'''
    bStr = ''
    if n < 0:  raise ValueError, "must be a positive integer"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1
    return bStr

def int2bin(n, count=24):
    """returns the binary of integer n, using count number of digits"""
    return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])

# this test runs when used as a standalone program, but not as an imported module
# let's say you save this module as den2bin.py and use it in another program
# when you import den2bin the __name__ namespace would now be  den2bin  and the
# test would be ignored
if __name__ == '__main__':
    print Denary2Binary(255)  # 11111111
    
    # convert back to test it
    print int(Denary2Binary(255), 2)  # 255
    
    print
    
    # this version formats the binary
    print int2bin(255, 12)  # 000011111111
    # test it
    print int("000011111111", 2)  # 255
    
    print

    # check the exceptions
    print Denary2Binary(0)
    print Denary2Binary(-5)  # should give a ValueError
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Added an explanation for testing with
if __name__ == '__main__':

Gribouillis 1,391 Programming Explorer Team Colleague
armored saint 0 Newbie Poster

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) #Change each integer to string
j=j+s #Add it to an empty string
j=j[::-1] #Reverse the string
return j

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are 1000 ways to do this, and you just added way #1001 :)

GothAlice 0 Newbie Poster

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.

def binary(n, digits=8):
    rep = bin(n)[2:]
    return ('0' * (digits - len(rep))) + rep
Gribouillis 1,391 Programming Explorer Team Colleague

About the formatting in the previous example, you can also use the format operator

def binary(n, digits=8):
    return "{0:0>{1}}".format(bin(n)[2:], digits)

See this snippet about the marvels of format().

Lardmeister 461 Posting Virtuoso

Lambda always intrigues me:

# works with IronPython, Python2 and Python3

d = 255
# a recursive dec to bin function
d2b = lambda d: (not isinstance(d,int) or (d==0)) and '0' \
    or (d2b(d//2)+str(d%2))

print(d2b(d))  # 011111111
tatetech 0 Newbie Poster

@ 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

#!/usr/bin/python   

                                                                              
""" make1DFractalBin.py                                                        

    arg1 = Natural(for order of fractal)        

    arg2 = Natural(in 512 -- 527, 576 -- 591, 640 -- 655, 704 --719,

         768 -- 783, 832 -- 847, 896 -- 911, 960 -- 975)  for mask)

    Generates a 1D fractal of order N,     

    where the fractal generated by 975 is   

    1. removing the middle third of each segment 

    2. stretching by 3                 

    equivalent to more complicated make1DFractal.py Natural 

"""


import sys

# convert a decimal integer to a binary string (base 2)

# tested with Python24 vegaseat 6/1/2005                

#                                                                              

def Denary2Binary(n):

  """convert denary integer n to binary string bStr"""

  bStr = ''

  if n < 0: raise ValueError, "must be a positive integer"

  if n == 0: return '0'

  while n > 0:

    bStr = str(n % 2) + bStr

    n = n >> 1

  return bStr 

  #                                  

def main():

  maskDec = 975 # generator for Sierpinski square  

  #Read commandline argument for order of fractal         

  if len(sys.argv) < 2:

    print "usage: $ python make1DFractalBin.py Natural(Order of fractal) [Natur\

al](default = 975, else see top of file for allowed generators)"

    sys.exit(2)

  else:

    order = int(sys.argv[1])

    print "Order of Fractal ordered: ", order, '\n'

    if len(sys.argv) ==3:

      maskDec = int(sys.argv[2])


  print "Generator = ", maskDec

  maskB = Denary2Binary(maskDec)

  print "Mask = \n",maskB


  iter = 0

  while iter < order:

    l = len(maskB)-1

""" multiply the mask by 2**(twice its binary length), and add its original value. This is equivalent to stretching it and removing middle third.

"""

    maskDec = maskDec*((3-1)**(2*l)) + maskDec

    maskB = Denary2Binary(maskDec)

    print maskB

    iter+=1


if __name__ == '__main__':

  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"!

whitelynx 0 Newbie Poster

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

>>> bin(10)[2:].rjust(8, '0')
'00001010'
Gribouillis 1,391 Programming Explorer Team Colleague

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

>>> bin(10)[2:].rjust(8, '0')
'00001010'

It's true, only in 2005 we were with python 2.4 which had no bin() function. Also it's useful for beginners to see how one can implement bin() in pure python. It is a classical exercise in programming to display numbers in a different basis.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.