TechAid24

Your Technical Consultant

Python Program to Convert Binary to Decimal & Back : Step-by-Step Guide

Posted on by Anonymous Guest 2 minutes read

A binary number is a number expressed in the base-2 numeral system or binary numeral system, which uses only two symbols, 0 and 1. The decimal numeral system is the standard system for denoting integer and non-integer numbers. In this article, we discuss a Python Program to Convert Binary to Decimal and back.

All decimal numbers can be converted to equivalent binary values and vice versa. For example, the binary equivalent of “2” is “10” To explore more, visit binary to decimal converter. In this article, we will create Python programs for converting a binary number into a decimal and vice versa

Convert Binary to Decimal

# Taking binary input
binary = input("Enter a binary number:")

# Calling the function
BinaryToDecimal(binary)


def BinaryToDecimal(binary): 
    decimal = 0 
    for digit in binary: 
        decimal = decimal*2 + int(digit) 
    print("The decimal value is:", decimal)
Output
Enter a binary number:10
The decimal value is: 2
Pythonic way to convert binary into decimal

We can use the built-in int() function to convert binary numbers into decimals. The int() function converts the binary string in base 2 number.

binary_string = input("Enter a binary number :")

try:
    decimal = int(binary_string,2)  
    print("The decimal value is :", decimal)    
    
except ValueError:
    print("Invalid binary number")
Output
Enter a binary number :10
The decimal value is : 2

Convert Decimal number into Binary number

decimal = input("Enter a decimal number :")

# Calling the function
DecimalToBinary(int(decimal))

def DecimalToBinary(decimal):       
    if decimal > 1: 
        DecimalToBinary(decimal // 2) 
    print(decimal % 2, end = '')
Output
Enter a decimal number :22
10110
Pythonic way to convert decimal into binary

Python has  bin() method to convert decimal numbers into binary. The bin() method converts and returns the binary equivalent string of a given integer.

decimal = input("Enter a binary number :")

binary = bin(int(decimal)).replace("0b", "")  
print("The decimal number is :", binary)
Output
Enter a binary number :10
The decimal number is : 1010

Tags:

Anonymous Guest

An anonymous author is a writer who conceals their true identity when publishing content, often for privacy, security, or confidentiality reasons. This approach is often used in technical articles to focus on the information being presented rather than the author's personal identity.

Leave a Reply

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