Octal to Decimal Conversion in Python
Octal to Decimal Conversion
Octal to Decimal conversion is the process of converting an octal number (base-8) into its equivalent decimal number (base-10). Each octal digit represents a power of 8.
For example, the octal number 17 is equal to decimal 15 because:
(1 × 8¹) + (7 × 8⁰) = 8 + 7 = 15
We will explore three methods to convert an octal number to a decimal number using Python programming.
Method 1: Using Loop
We extract each digit of the octal number, multiply it by the corresponding power of 8, and sum the results.
def octal_to_decimal(octal): decimal, i = 0, 0 while octal: last_digit = octal % 10 decimal += last_digit * (8 ** i) octal //= 10 i += 1 return decimal # Get user input octal = int(input("Enter an octal number: ")) print("Decimal equivalent:", octal_to_decimal(octal))
Output:
Enter an octal number: 17 Decimal equivalent: 15
Method 2: Using Built-in Function
We can use Python's int() function to directly convert an octal number to a decimal number.
# Get user input octal = input("Enter an octal number: ") # Convert using built-in function decimal = int(octal, 8) print("Decimal equivalent:", decimal)
Output:
Enter an octal number: 17 Decimal equivalent: 15
Method 3: Using Recursion
We recursively extract each digit and multiply it by the corresponding power of 8.
def octal_to_decimal_recursive(octal, power=0): if octal == 0: return 0 return (octal % 10) * (8 ** power) + octal_to_decimal_recursive(octal // 10, power + 1) # Get user input octal = int(input("Enter an octal number: ")) print("Decimal equivalent:", octal_to_decimal_recursive(octal))
Output:
Enter an octal number: 17 Decimal equivalent: 15