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
            
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python