We need to write a python program which converts a binary input to a decimal number.

Example:

Binary to Decimal

This can be achieved in multiple ways.

Convert Binary to Decimal in Python

In this method we will convert binary into decimal in a standard way. All we need to do is to multiple each of the binary digits with its corresponding value of 2 raised to the power to its index (position from right – 1) and sum them up.

Output

Convert Binary to Decimal in Python using int()

int() method can also convert a binary into an integer, if we pass the binary number along with its base (i.e 2) to int() method.

Output

Convert Binary to Decimal in Python using Recursion

This method is similar to the first example, only we are implementing it in a recursive way. In the recursive function, we are passing the binary number. Then we are multiplying the first digit of the binary number to its corresponding value of 2 raised to the power of its index (i.e position from the right end – 1). Then we need to add the result of multiplication to the next recursive call by passing the updated binary (i.e removing the first digit). This process will continue until the single last digit of the number. The result of each recursive call will be added and finally will be returned to the first recursive function call.

Output

If you have any suggestion or doubts then comment below.

Leave a Reply

Close Menu