Python Program for Binary To Decimal Conversion

Binary to Decimal Conversion

In this article we will discuss binary to decimal conversion in Python. For this purpose we need to take a binary integer number from user and convert that binary integer number to its decimal equivalent form and then print the converted number on to the screen. A Decimal number can be calculated by multiplying every digits of binary number with 2 to the power of the integers starts from 0 to n-1 where n refers as the total number of digits present in a binary number and finally add all of them.

In number system, Binary number contains only two digits of 0, 1 which has base 2. Whereas Decimal Number contains only 10 Symbols: 0, 1, 2, 3, 4, 5, 6, 7 , 8 and 9 which has base 10.

For example:

101 in base 2(Binary) => 5 in base 10(decimal)

100101 in base 2(Binary) => 37 in Base 10 (Decimal)

Binary to decimal conversion


Step 1. Start

Step 2. Take a user input and store into int datatype variable say num.

Step 3. Store num variable value to binary_val variable.

Step 4. Store 0 to decimal_val variable.

Step 5. Store 1 to base variable variable.

Step 6. Run a while loop until num variable is greater than 0 i.e,( num > 0).

Step 7. Store remainder value to rem variable after solving num % 10.

Step 8. Store decimal_val + rem * base value into decimal_val.

Step 9. Store the value (num // 10) into num variable.

Step 10. Store the value (base * 2)  into base variable.

Step 11. Print  decimal_val value that contain the converted binary to decimal value.

Step 12. Stop

Binary to decimal conversion in C++

Program for Binary to Decimal conversion in Python :

num = int(input("Enter number:"))
binary_val = num
decimal_val = 0
base = 1
while num > 0:
    rem = num % 10
    decimal_val = decimal_val + rem * base
    num = num // 10
    base = base * 2

print("Binary Number is {} and Decimal Number is {}".format(binary_val, decimal_val))

# This code is contributed by Shubhanshu Arya (Prepinsta Placement Cell Student) 


Enter number:10
Binary Number is 10 and Decimal Number is 2

Time and Space Complexities

Time Complexity – O(K), where K is the count of the digits in the binary number

Space Complexity – O(1), Constant Space

One comment on “Python Program for Binary To Decimal Conversion”