bin () in Python

File handling | Loops | Python Methods and Functions | String Variables

Naive methods for decimal to binary conversion

1. Using recursion

# Function for printing a binary number for
# entering a decimal numbers using recursion

def decimalToBinary (n):

 

if n & gt;  1 :

# share with cumulative result

# (cancel remainder)

decimalToBinary (n / / 2

 

 

  print (n % 2 , end = "") 

 
# Driver code

if __ name__  = = '__main__' :

  decimalToBinary ( 8 )

print ( "" )

decimalToBinary ( 18 )

print ( "" )

decimalToBinary ( 7 )

  print

 

Output:

 1000 10010 111 

2. Using the loop

# Python code to demonstrate the naive method
# using loop

 
# function that returns a binary string

def Binary (n):

binary = ""

i = 0

while n & gt;  0 and i & lt; = 8 :

  s1 = str ( int (n % 2 ))

  binary = binary + s1

  n / = 2

i = i + 1

  d = binary [:: - 1 ]

  return d

  

print ( "The binary representation of 100 (using loops) is: " , end = " ")

print (Binary ( 100 ))

Output:

 The binary representation of 100 (using loops) is: 001100100 

Using bin ()

Using bin () reduces the time required for coding and also removes the difficulties you might see in the above two methods.

  Syntax:  bin (a)  Parameters:   a:  an integer to convert  Return Value:  A binary string of an integer or int object.  Exceptions:  Raises TypeError when a float value is sent in arguments. 

# Python code to demonstrate how it works
# bin ()

 
# function that returns a binary string

def Binary (n):

s = bin (n)

 

# remove the prefix & quot; 0b & quot;

s1 = s [ 2 :]

return s1

 

print ( "The binary representation of 100 (using bin ()) is:" , end = "")

print (Binary ( 100 ))

Output:

 The binary representation of 100 (using bin ()) is: 1100100 

This article courtesy of Manjit Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials