HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Convert Binary String to Decimal Number Vice versa

Understanding how to convert between binary and decimal numbers is fundamental in computer science and programming.

In this article, I’ll show you the Python functions that enable you to seamlessly convert binary numbers to their decimal counterparts and vice versa.

Convert Binary String to Decimal Number

Below is my code which performs the conversion:

def binary_to_decimal(binary_str):
    decimal = 0
    power = len(binary_str) - 1
    
    for digit in binary_str:
        if digit == '1':
            decimal += 2 ** power
        power -= 1
    
    return decimal

# Example showing how to use the above function
binary_num = "1010"
decimal_num = binary_to_decimal(binary_num)
print("Decimal equivalent of", binary_num, "is", decimal_num)

Output:

Decimal equivalent of 1010 is 10

Let me explain the conversion steps to you.

  • Start by setting decimal to 0, which will store the decimal equivalent, and power to the length of the binary number minus 1. power is used to calculate the position value of each binary digit.
  • Loop through each digit in the binary number from left to right.
  • For each binary digit, if it’s ‘1’, add 2 raised to the power of its position value (power) to the decimal variable.
  • After processing each digit, decrement the power variable by 1 to move to the next lower position value.
  • Once all digits are processed, return the decimal variable, which now holds the decimal equivalent of the binary number.

These are simple steps, you can accurately convert any binary number to its decimal representation using the provided Python code.

Convert Decimal Number to Binary

Below is my code which performs the reverse conversion:

def decimal_to_binary(decimal_num):
    binary = ""
    
    while decimal_num > 0:
        remainder = decimal_num % 2
        binary = str(remainder) + binary
        decimal_num //= 2
    
    return binary if binary else "0"

# Example showing how to use the above function
decimal_num = 10
binary_num = decimal_to_binary(decimal_num)
print("Binary equivalent of", decimal_num, "is", binary_num)

Output:

Binary equivalent of 10 is 1010

Let’s explain the steps involved in converting a decimal to binary:

  • Begin by setting an empty string binary which will store the binary equivalent of the decimal number.
  • Start a loop where you repeatedly divide the decimal number by 2 until it becomes 0. This process is often referred to as “integer division”.
  • For each division, calculate the remainder (remainder) by taking the modulo 2 of the current decimal number.
  • Add the remainder to the left side of the binary string. This is done because we’re building the binary number from right to left.
  • Update the decimal number by performing integer division by 2, effectively shifting it to the right by one position.
  • Continue this process until the decimal number becomes 0.
  • Once the decimal number becomes 0, return the binary string, which now holds the binary equivalent of the original decimal number.

With these above 2 examples, you can accurately convert any decimal number to its binary representation and vice versa. You can contact me for any doubts or clarifications.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Get Current Day of Week
Up Next
Python Code to Find Difference Between 2 Strings
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.