Q:

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

belongs to collection: Python basic programs

0

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

Example:

    Input: 
    1010

    Output: 
    10

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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     

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Convert the decimal number to binary with... >>
<< Python program to find the solution of a special s...