Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Convert Binary number to Octal

Converting a binary number to an octal number involves grouping the binary digits into sets of three (starting from the right) and then converting each set to its corresponding octal digit. This conversion can be easily implemented in various programming languages such as C, C++, Python, and Java.

(a.) C Code

#include <stdio.h>
#include <string.h>
#include <math.h>

int binaryToOctal(long long binary) {
int octal = 0, decimal = 0, i = 0;

// Convert binary to decimal
while (binary != 0) {
    decimal += (binary % 10) * pow(2, i);
    ++i;
    binary /= 10;
}

// Convert decimal to octal
i = 1;
while (decimal != 0) {
    octal += (decimal % 8) * i;
    decimal /= 8;
    i *= 10;
}

return octal;
}

int main() {
long long binary;
printf("Enter a binary number: ");
scanf("%lld", &binary);
printf("Octal equivalent: %d
", binaryToOctal(binary));
return 0;
}
      
Output:-
Enter a binary number: 110110
Octal equivalent: 66

(b.) C++ Code

#include <iostream>
#include <cmath>
using namespace std;

int binaryToOctal(long long binary) {
int octal = 0, decimal = 0, i = 0;

// Convert binary to decimal
while (binary != 0) {
    decimal += (binary % 10) * pow(2, i);
    ++i;
    binary /= 10;
}

// Convert decimal to octal
i = 1;
while (decimal != 0) {
    octal += (decimal % 8) * i;
    decimal /= 8;
    i *= 10;
}

return octal;
}

int main() {
long long binary;
cout << "Enter a binary number: ";
cin >> binary;
cout << "Octal equivalent: " << binaryToOctal(binary) << endl;
return 0;
}
Output:-
Enter a binary number: 110110
Octal equivalent: 66

(c.) Python Code

def binary_to_octal(binary):
decimal = int(binary, 2)
octal = oct(decimal)
return octal[2:]

binary = input("Enter a binary number: ")
print("Octal equivalent:", binary_to_octal(binary))
Output:-
Enter a binary number: 110110
Octal equivalent: 66

(d.) Java Code

import java.util.Scanner;

public class BinaryToOctal {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a binary number: ");
    String binary = scanner.nextLine();
    int decimal = Integer.parseInt(binary, 2);
    String octal = Integer.toOctalString(decimal);
    System.out.println("Octal equivalent: " + octal);
}
}
Output:-
Enter a binary number: 110110
Octal equivalent: 66