Google News
logo
C++ Program to Convert Binary Number to Octal and Vice-Versa
In the following example of C++ program to convert a binary number to octal and vice versa :
Program :
#include <iostream>
#include <cmath>
using namespace std;

// function to convert binary to decimal
int binaryToDecimal(long long n) {
    int decimal = 0, i = 0;

    while (n > 0) {
        int digit = n % 10;
        decimal += digit * pow(2, i);
        n /= 10;
        i++;
    }

    return decimal;
}

// function to convert decimal to octal
int decimalToOctal(int n) {
    int octal = 0, i = 1;

    while (n > 0) {
        int digit = n % 8;
        octal += digit * i;
        n /= 8;
        i *= 10;
    }

    return octal;
}

// function to convert binary to octal
long long binaryToOctal(long long binary) {
    int decimal = binaryToDecimal(binary);
    long long octal = decimalToOctal(decimal);
    return octal;
}

// function to convert octal to binary
long long octalToBinary(long long octal) {
    int decimal = 0, i = 0;

    while (octal > 0) {
        int digit = octal % 10;
        decimal += digit * pow(8, i);
        octal /= 10;
        i++;
    }

    long long binary = 0;
    i = 1;

    while (decimal > 0) {
        int digit = decimal % 2;
        binary += digit * i;
        decimal /= 2;
        i *= 10;
    }

    return binary;
}

int main() {
    int choice;
    long long n;

    cout << "Choose an option:\n";
    cout << "1. Binary to Octal\n";
    cout << "2. Octal to Binary\n";
    cin >> choice;

    switch (choice) {
        case 1:
            cout << "Enter a binary number: ";
            cin >> n;
            cout << "Octal equivalent: " << binaryToOctal(n) << endl;
            break;

        case 2:
            cout << "Enter an octal number: ";
            cin >> n;
            cout << "Binary equivalent: " << octalToBinary(n) << endl;
            break;

        default:
            cout << "Invalid choice.\n";
            break;
    }

    return 0;
Output :
Choose an option:
1. Binary to Octal
2. Octal to Binary

1
Enter a binary number: 101110
Octal equivalent: 56

 

Choose an option:
1. Binary to Octal
2. Octal to Binary

2
Enter an octal number: 56
Binary equivalent: 101110
This program prompts the user to choose between converting a binary number to octal or an octal number to binary. Depending on the choice, the program either calls binaryToOctal or octalToBinary to perform the conversion.

binaryToOctal first converts the binary number to decimal using binaryToDecimal and then converts the decimal number to octal using decimalToOctal. octalToBinary first converts the octal number to decimal by repeatedly multiplying each digit by the corresponding power of 8 and summing the results. The decimal number is then converted to binary using a method similar to decimalToOctal.