Python | Convert the binary number to decimal without using library function

Binary to decimal in Python: Here, we are going to learn how to convert the given binary number to the decimal number without using any library function in Python? By IncludeHelp Last updated : January 04, 2024

Problem statement

Given a binary number and we have to convert it into decimal without using library function.

Example

Consider the below example with sample input and output:

Input: 
1010

Output: 
10

Algorithm

The steps (algorithm) to convert a binary number to decimal are:

  1. Input a binary number
  2. Run a loop till the given number is not 0.
  3. Starting from the right, extract the digit by dividing the number by 10.
  4. Multiply each digit by its corresponding power of 2.
  5. Sum all the results to get the decimal value, and return it.
  6. Print the result.

Python code to convert binary to decimal

# Python code to convert binary to decimal
def binToDec(bin_value):
    
    # converting binary to decimal
    decimal_value = 0
    count = 0
    
    while(bin_value != 0):
        digit = bin_value % 10
        decimal_value = decimal_value + digit * pow(2, count)
        bin_value = bin_value//10
        count += 1

    # returning the result        
    return decimal_value

# main code
if __name__ == '__main__':
    binary = int(input("Enter a binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))

    binary = int(input("Enter another binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))

    binary = int(input("Enter another binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))  

Output

The output of the above example is:

Enter a binary value: 1010  
decimal of binary  1010  is:  10  
Enter another binary value: 1111000011  
decimal of binary  1111000011  is:  963 
Enter another binary value: 10000001 
decimal of binary  10000001  is:  129     

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.