Decimal to Octal Conversion in Python
Decimal to Octal Conversion
Decimal to Octal conversion is the process of converting a decimal number (base-10) into its equivalent octal number (base-8). Each octal digit represents a power of 8.
For example, the decimal number 31 is equal to octal 37 because:
(3 × 8¹) + (7 × 8⁰) = 24 + 7 = 31
We will explore three methods to convert a decimal number to an octal number using Python programming.
Method 1: Using Division by 8
We divide the decimal number by 8 repeatedly, storing the remainders. These remainders represent the digits of the octal number from least significant to most significant.
def decimal_to_octal(decimal): octal = [] while decimal > 0: octal.append(str(decimal % 8)) decimal = decimal // 8 octal.reverse() # Reverse to get the correct order print("Octal equivalent:", ''.join(octal)) decimal = int(input("Enter a decimal number: ")) decimal_to_octal(decimal)
Output:
Enter a decimal number: 31 Octal equivalent: 37
Method 2: Using `oct()` Built-in Function
Python has a built-in function oct() that can directly convert a decimal number to its octal string representation. The result includes a prefix 0o to denote it's an octal number.
decimal = int(input("Enter a decimal number: ")) octal = oct(decimal) print("Octal equivalent:", octal[2:]) # Remove the '0o' prefix
Output:
Enter a decimal number: 31 Octal equivalent: 37
Method 3: Using Recursion
We can convert a decimal number to octal recursively. The recursive function divides the number by 8 and prints the remainders, which form the octal digits.
def decimal_to_octal_recursive(decimal): if decimal == 0: return '' return decimal_to_octal_recursive(decimal // 8) + str(decimal % 8) decimal = int(input("Enter a decimal number: ")) if decimal == 0: print("Octal equivalent: 0") else: print("Octal equivalent:", decimal_to_octal_recursive(decimal))
Output:
Enter a decimal number: 31 Octal equivalent: 37