Program for Binary to Octal Conversion in Python
Binary to Octal Conversion
Converting a binary number to octal involves grouping binary digits into sets of three from right to left and converting each set to its octal equivalent.
We will explore three methods to perform this conversion using Python programming.
Method 1: Using Built-in Function
Python provides built-in functions to directly convert binary to octal.
binary = input("Enter a binary number: ") decimal = int(binary, 2) octal = oct(decimal)[2:] print("Octal:", octal)
Example Output:
Enter a binary number: 101101 Octal: 55
Method 2: Using Division by 8
We manually convert binary to decimal and then divide the decimal number by 8 to get the octal equivalent.
def binary_to_decimal(binary): decimal = 0 base = 1 while binary > 0: decimal += (binary % 10) * base binary //= 10 base *= 2 return decimal def decimal_to_octal(decimal): octal = "" while decimal > 0: octal = str(decimal % 8) + octal decimal //= 8 return octal or "0" binary = int(input("Enter a binary number: ")) decimal = binary_to_decimal(binary) print("Octal:", decimal_to_octal(decimal))
Example Output:
Enter a binary number: 111001 Octal: 71
Method 3: Using Recursion
We use recursion to first convert binary to decimal and then recursively convert decimal to octal.
def binary_to_decimal_recursive(binary): if binary == 0: return 0 return (binary % 10) + 2 * binary_to_decimal_recursive(binary // 10) def decimal_to_octal_recursive(decimal): if decimal == 0: return "" return decimal_to_octal_recursive(decimal // 8) + str(decimal % 8) binary = int(input("Enter a binary number: ")) decimal = binary_to_decimal_recursive(binary) octal = decimal_to_octal_recursive(decimal) or "0" print("Octal:", octal)
Example Output:
Enter a binary number: 100110 Octal: 46