Binary to Decimal Conversion Program


Binary to Decimal Conversion Program in Python

This guide explains how to write a Python program to convert binary numbers to decimal numbers. The program is structured with clear documentation for each part of the code.

Program Structure and Explanation

The program consists of the following parts:

  • Function to convert a binary string to a decimal number
  • Main block to take input and display the result
  • Documentation for each part of the code

Python Code


# Function to convert binary to decimal
def binary_to_decimal(binary_str):
    """
    Convert a binary string to a decimal number.

    Parameters:
    binary_str (str): A string representing a binary number (e.g., "1010").

    Returns:
    int: The decimal representation of the binary number.
    """
    decimal_number = 0
    for index, digit in enumerate(binary_str[::-1]):
        if digit == '1':
            decimal_number += 2 ** index
    return decimal_number

# Main block
if __name__ == "__main__":
    """
    Main block to take binary input from the user and print the decimal output.
    """
    # Taking binary input from the user
    binary_input = input("Enter a binary number: ")
    
    # Validating the input
    if all(char in '01' for char in binary_input):
        # Converting binary to decimal
        decimal_output = binary_to_decimal(binary_input)
        print(f"The decimal representation of binary {binary_input} is {decimal_output}.")
    else:
        print("Invalid binary number. Please enter a binary number containing only 0s and 1s.")
    

Explanation

Function: binary_to_decimal

The binary_to_decimal function converts a binary string to a decimal number. Here is how it works:

  1. Initialization: A variable decimal_number is initialized to 0. This variable will store the final decimal number.
  2. Iteration: The function iterates over the binary string in reverse order (using enumerate to get both the index and the digit).
  3. Conversion: For each ‘1’ in the binary string, the function adds 2 raised to the power of the index to decimal_number.
  4. Return: The function returns the calculated decimal number.

Main Block

The main block of the program does the following:

  1. Input: Takes a binary number as input from the user.
  2. Validation: Checks if the input string contains only ‘0’ and ‘1’. If not, it prints an error message.
  3. Conversion: Calls the binary_to_decimal function to convert the binary string to a decimal number.
  4. Output: Prints the decimal representation of the binary number.

This program provides a simple and effective way to convert binary numbers to decimal using Python, with clear documentation for better understanding and maintainability.


By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)