Python Decimal to Binary Converter

By | July 21, 2019

Python Decimal to Binary Converter – This Python tutorial explains the logic to convert a decimal number into its corresponding binary number.

How To convert a Decimal Number into Binary Number

  1. We divide the decimal number by base 2 and get the quiotient and remainder.  Example: divide 5 by 2, quotient1 is 2 and remainder1 is 1.
  2. Then we divide the quotient by base 2 and get the quotient and remainder. The Example continues from step 1: divide quotient1 by 2, quotient2 is 1 and remainder2 is 0 (zero).
  3. This process continues until the quotient bcomes zero. The example continues from step 2: divide quotient2 by 2, now quotient3 is 0 (zero), so we stop, and remainder3 is 1.
  4. Now we write all remainders in reverse order to get the required binary number. The example continus from step 3. We will write remainder3,remainder2,remainder1 (in reverse order) so that we will get the required binary number 101.
Python Program Decimal to Binary

Python Program Decimal to Binary

 

The Source Code of Python Program Decimal to Binary Converter Using while loop

# This Python script / program is used to input
# a decimal number and convert into binary number
# using a while loop
# author: www.EasyCodeBook.com (c)

num = int(input('Enter a Decimal number to Convert into Binary:'))
q=num
binary=0
i=0

while q!=0:
    rem = q%2
    binary = binary + rem * (10**i)
    q = q // 2
    i+=1

print('Binary Number=',binary)
    

The output of Decimal to binary converting program is as follows:

Enter a Decimal number to Convert into Binary:15
Binary Number= 1111

Leave a Reply

Your email address will not be published. Required fields are marked *