PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Convert Decimal Number to Binary and Vice Versa

Python Convert Decimal Number to Binary and Vice Versa

Updated on: April 22, 2025 | Leave a Comment

Converting numbers between different numeral systems is a common task in programming. One of the most fundamental conversions is from decimal (base-10) to binary (base-2). This is especially important in computer science, as binary numbers are the foundation of all digital systems.

  • A decimal number is based on 10 and uses digits from 0 to 9. Examples: 25, 123, 10.
  • A binary number is based on 2 and uses only two digits, 0 and 1. An example is 1010 (which is 10 in decimal).

This article will explore how to convert a decimal number to binary and vice versa using Python, covering multiple approaches, code examples, and explanations.

Table of contents

  • Convert Decimal to Binary
    • 1. Using Python’s Built-in bin() Function
    • 2. Using format() Function
    • 3. Using F-String Formatting
    • 4. Using While Loop
    • 5. Using Recursion
  • Convert Binary to Decimal
    • 1. Using Built-in int() with Base 2
    • 2. Manual Conversion Using Loop
  • Summary

Convert Decimal to Binary

1. Using Python’s Built-in bin() Function

The bin() function in Python converts an integer number into its binary string representation.

Syntax: bin(x)

  • x must be an integer (can be positive or negative).
  • Returns a string that starts with '0b', followed by the binary representation of the integer.
  • For Example, bin(5) = '0b101'

Use the below syntax if you want to remove the ‘0b’ prefix:

binary = bin(5)[2:] # Output: '101'

Note: [2:] slices a string from index 2 to the end, skipping the first two characters.

Code Example

decimal = 20
binary = bin(decimal)
print(f"Binary of {decimal} is {binary[2:]}")Code language: Python (python)

Output:

Binary of 20 is 10100

2. Using format() Function

The format() function in Python converts an integer decimal to its binary representation as a string, without the '0b' prefix.

Syntax: format(x, 'b')

  • x must be an integer (can be positive or negative).
  • Returns a string of binary representation of the integer.
  • For Example, format(5, 'b') = '101'

Note: No '0b' like with bin().

Code Example

decimal = 20
binary = format(decimal, 'b')
print(f"Binary of {decimal} is {binary}")

# Output:
# Binary of 20 is 10100Code language: Python (python)

3. Using F-String Formatting

An F-string (formatted string literal) lets you embed variables, expressions, or formatting instructions directly into a string using {}.

Just prefix the string with f or F and place variables or expressions inside {}.

For Example,

name = "Alice"
age = 25
f"My name is {name} and I am {age} years old."    # Output: My name is Alice and I am 25 years old.Code language: Python (python)

Numbers can be formatted like this:

f"{3.14159:.2f}" # '3.14' → 2 decimal places
f"{255:x}" # 'ff' → hexadecimal of 255

f"{{5:b}}" # '101' → binary of 5
<strong>:b inside the f-string formats the decimal as binary</strong>Code language: Python (python)

Code Example

decimal = 20
print(f"Binary of {decimal} is {decimal:b}")

# Output:
# Binary of 20 is 10100Code language: Python (python)

4. Using While Loop

In this approach, we manually convert the decimal number into a binary number using while loop.

Algorithm to convert Decimal to Binary in Python:

  1. Divide the decimal number by 2
  2. Record the remainder
  3. Repeat the process with the quotient
  4. Reverse the remainders to get the binary value

For Example:

Convert 10 to binary
→ 10 ÷ 2 = 5 remainder 0
→ 5 ÷ 2 = 2 remainder 1
→ 2 ÷ 2 = 1 remainder 0
→ 1 ÷ 2 = 0 remainder 1
Binary = 1010

Code Example

decimal = 20
binary = ""

if decimal == 0:
    binary = "0"
else:
    while decimal > 0:
        remainder = decimal % 2  # Get the remainder which is the last binary digit (0 or 1)
        binary = str(remainder) + binary  # Add it to the front of the result
        decimal = decimal // 2  # Divide number by 2 (integer division)

print(binary)

# Output:
# 10100
Code language: Python (python)

5. Using Recursion

Recursion is a technique where a function calls itself to solve smaller parts of a problem until a base condition is met. It’s like solving a big problem by breaking it into smaller versions of the same problem.

In this approach, the algorithm used to convert decimals to binary is the same as explained in the above approach.

Step-by-step:

  1. It keeps dividing the number by 2, again and again.
  2. When it can’t divide anymore (when n is 1 or 0), it stops.
  3. As it comes back up (returns from each call), it prints the remainders (which are 1s and 0s).
  4. These remainders make up your binary number!

For Example: Convert 10 to Binary

10 // 2 = 5 → remainder = 0
5 // 2 = 2 → remainder = 1
2 // 2 = 1 → remainder = 0
1 is the stopping point → remainder = 1

Now we print the remainders from last to first: 1 → 0 → 1 → 0 → output = 1010

Function Calls Breakdown:

  1. decimal_to_binary(10)
    • Calls decimal_to_binary(10 // 2) i.e. decimal_to_binary(5)
    • Prints: n % 2 = 10 % 2 = 0 (after the recursive call)
  2. decimal_to_binary(5)
    • Calls decimal_to_binary(2)
    • Prints: 5 % 2 = 1
  3. decimal_to_binary(2)
    • Calls decimal_to_binary(1)
    • Prints: 2 % 2 = 0
  4. decimal_to_binary(1)
    • Does NOT call again (base case: n <= 1)
    • Prints: 1 % 2 = 1

Code Example

def decimal_to_binary(n):
    if n > 1:
        decimal_to_binary(n // 2)
    print(n % 2, end='')

decimal = 20
print("Binary is: ", end='')
decimal_to_binary(decimal)

# Output:
# Binary is: 10100Code language: Python (python)

Convert Binary to Decimal

1. Using Built-in int() with Base 2

In this approach, we will be using the built-in function int() which converts a binary string to a decimal integer.

Syntax: int(x, base)

  • x: A string or number (in our case, a binary string, like "1010")
  • base: The base of the number system (2 for binary)
  • For Example: int("1010", 2) # Output: 10

Code Example

binary = "1010"
decimal = int(binary, 2)
print(f"Decimal value of {binary} is {decimal}")

# Output:
# Decimal value of 1010 is 10Code language: Python (python)

2. Manual Conversion Using Loop

This approach does not use the built-in function but manually convert the Binary number into Decimal Number using for loop in Python.

How it works:

Binary is base-2, meaning each digit represents a power of 2, from right to left. It parses the string "1010" as a binary number, as follows:

( 1 × 2³ ) + ( 0 × 2² ) + ( 1 × 2¹ ) + ( 0 × 2⁰ ) 
= 8 + 0 + 2 + 0
= 10

Code Example

binary = "1010"
decimal = 0
power = 0

for digit in reversed(binary):
    decimal += int(digit) * (2 ** power)
    power += 1

print(f"Decimal value is {decimal}")

# Output:
# Decimal value is 10Code language: Python (python)

Explanation

  1. Start with two variables:
    • decimal = 0 → This will store the final decimal result.
    • power = 0 → Keeps track of the power of 2 (starts from rightmost digit).
  2. reversed(binary): We reverse the binary string so we can process it from right to left, starting from the least significant bit (LSB) — the one at the end.
  3. For each digit in the reversed binary string:
    • Convert the digit from string to integer: int(digit)
    • Multiply the digit by 2 ** power (power of 2)
    • Add the result to the decimal variable
    • Increase power by 1 (to move to the next binary digit’s place value)
  4. After the loop ends, the decimal variable holds the final decimal value.
  5. Print or return the decimal result.

Let’s walk through the loop for "1010":

Initial values:

  • decimal = 0
  • power = 0

Loop iterations:

  1. First digit (LBS): ‘0’
    → decimal += 0 * 2^0 = 0
    → power = 1
  2. Second digit: ‘1’
    → decimal += 1 * 2^1 = 2
    → power = 2
  3. Third digit: ‘0’
    → decimal += 0 * 2^2 = 0
    → power = 3
  4. Fourth digit: ‘1’
    → decimal += 1 * 2^3 = 8
    → power = 4

Final result: decimal = 0 + 2 + 0 + 8 = 10

Summary

Python offers multiple ways to convert a decimal number to binary and vice versa. You can use built-in functions like bin(), int(), format(), and f-strings for quick solutions, or write manual or recursive methods to understand the logic deeply.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com