Binary to Decimal Conversion in Python
Binary to Decimal Conversion
Binary to Decimal conversion is the process of converting a binary number (base-2) into its equivalent decimal number (base-10). Each binary digit represents a power of 2.
For example, the binary number 1010 is equal to decimal 10 because:
(1 × 2³) + (0 × 2²) + (1 × 2¹) + (0 × 2⁰) = 8 + 0 + 2 + 0 = 10
We will explore three methods to convert a binary number to a decimal number using Python programming.
Method 1: Using Loop
def binary_to_decimal(binary): decimal, i = 0, 0 while binary: last_digit = binary % 10 decimal += last_digit * (2 ** i) binary //= 10 i += 1 return decimal
Output:
Enter a binary number: 1010 Decimal equivalent (Loop): 10
Method 2: Using Recursion
def binary_to_decimal_recursive(binary, i=0): if binary == 0: return 0 return (binary % 10) * (2 ** i) + binary_to_decimal_recursive(binary // 10, i + 1)
Output:
Enter a binary number: 1010 Decimal equivalent (Recursion): 10
Method 3: Using Built-in Function
def binary_to_decimal_builtin(binary): return int(str(binary), 2)
Output:
Enter a binary number: 1010 Decimal equivalent (Built-in): 10
Main Function
binary = int(input("Enter a binary number: ")) print(f"Decimal equivalent (Loop): {binary_to_decimal(binary)}") print(f"Decimal equivalent (Recursion): {binary_to_decimal_recursive(binary)}") print(f"Decimal equivalent (Built-in): {binary_to_decimal_builtin(binary)}")