As we have seen in the previous article, the various ways in which we can convert from decimal to binary. Let us now explore the reverse that is Binary to Decimal Conversion in Python. Imagine that we are given a string that represents binary value of a number, we need to write a function that accepts this string and converts it into decimal equivalent. For example if the number 110 is given as the input to the function, it should return 6 as the output.
We can write 6 as 4+2, the powers of 6 in two would be: 1/4, 1/2, 0/1. If we see 17, we can write it as 16+1 we get the highest power smaller than or equal to 17: 1/16, 0/8, 0/4, 0/2 & 1/1
Implementation of Binary to Decimal Conversion in Python
Let us understand the process undertaken to convert Binary numbers to Decimal. In binary representation every bit represents a power of 2, we need to traverse through each individual bit and multiply them with the corresponding power. For example with the number ‘1100’:
0 x 20+ 0 x 21 + 1 x 22 + 1 x 23
If the number was ‘10001’:
Once we add the terms with the results, we obtain the end result.
# Taking binary input binary = input("Enter a binary number:") def BinaryToDecimal(binary): decimal = 0 for digit in binary: decimal = decimal*2 + int(digit) print("The decimal value is:", decimal) # Calling the function BinaryToDecimal(binary)
Alternative method for Binary to Decimal Conversion in Python
We can also obtain the decimal representation of a binary number in Python by using the built-in function:
b=input("Enter binary number: ") def BinToDec(b): res=int(b,2) print(res) BinToDec(b)
Output: Enter binary number: 1100 12
Thus, we have seen the two ways in which we can convert Binary numbers to Decimal representation. In the next article we will explore Slicing in Lists, Tuples and Strings.