How to Convert Binary to Decimal in Python

In this article, we will learn to convert a binary number into a decimal number. Given a binary number, we need to convert the binary number to its equivalent decimal form.
Using loop
def binaryToDecimal(b): d , i, n = 0, 0, 0 while (b != 0): dec = b % 10 d = d + dec * pow(2, i) b = b//10 i += 1 print(d) binaryToDecimal(10010) binaryToDecimal(10110) binaryToDecimal(10110101001)
Output:
18 22 1449
Using int()
int() will convert the binary number with the base of 2, resulting in a decimal number. While using int(), the binary number must be passed as string. int() can’t convert non-string with explicit base
def binaryToDecimal(b): return int(b, 2) print("Decimal of 10010 is ", binaryToDecimal('10010')) print("Decimal of 101101 is ", binaryToDecimal('101101')) print("Decimal of 10110101001 is ", binaryToDecimal('10110101001'))
Output:
Decimal of 10010 is 18 Decimal of 101101 is 45 Decimal of 10110101001 is 1449
Subscribe
Login
Please login to comment
0 Discussion