Python Program to Convert Decimal Number into Binary

In computer science, binary code is used to represent numbers, letters, and symbols. Binary Code contains only two distinct digits, 0 and 1. Converting decimal numbers into binary code requires some basic operation. In this post, we will discuss writing a Python program to convert decimal numbers to binary code.

The binary number system is a base-2 number system and the decimal number system is a base-10 number system. It means binary numbers can have only two possible values, 0 or 1. Whereas decimal numbers can have ten possible values, 0 through 9.

Steps require To convert a decimal number to binary:

  1. Divide the decimal number by 2.
  2. Record the remainder of the division as the first binary digit (0 or 1).
  3. Divide the quotient from step 1 by 2.
  4. Record the remainder of the division as the second binary digit.
  5. Repeat steps 3-4 until the quotient is 0.
  6. Write the binary digits in reverse order (starting from the last remainder).

For example, to convert the decimal number 13 to binary:

  1. 13 / 2 = 6 remainder 1
  2. 6 / 2 = 3 remainder 0
  3. 3 / 2 = 1 remainder 1
  4. 1 / 2 = 0 remainder 1
  5. The binary digits are 1101 (in reverse order)

There are multiple ways to write a Python program to convert a decimal number to binary.

Method 1: Convert Decimal to Binary Using Loop

decimal = temp = int(input("Please Enter a decimal number: "))
binary = ""
while temp > 0:
    remainder = temp % 2
    binary = str(remainder) + binary
    temp = temp // 2
print("Binary number is ", binary, " for ", decimal)

Output

Please Enter a decimal number: 13
Binary number is 1101 for 13

Method 2: Decimal to Binary Using bin() function in Python

This is the simplest way to convert a given decimal number to binary in Python is using the built-in bin() function. The bin() function takes a decimal number as input and returns its binary equivalent.

decimal = int(input("Please Enter a decimal number: "))
binary = bin(decimal)
print("Binary number is ", binary[2:], " for ", decimal)

Output

Please Enter a decimal number: 34
Binary number is  100010  for  34