Convert Binary to Octal

Convert Binary to Octal in C++ (5 Programs)

IntermediateTopic: Advanced Number Programs
Back

C++ Convert Binary to Octal Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <cmath>
using namespace std;

int binaryToDecimal(long long binary) {
    int decimal = 0, i = 0, remainder;
    while (binary != 0) {
        remainder = binary % 10;
        binary /= 10;
        decimal += remainder * pow(2, i);
        ++i;
    }
    return decimal;
}

int decimalToOctal(int decimal) {
    long long octal = 0;
    int remainder, i = 1;
    while (decimal != 0) {
        remainder = decimal % 8;
        decimal /= 8;
        octal += remainder * i;
        i *= 10;
    }
    return octal;
}

int main() {
    long long binary;
    cout << "Enter a binary number: ";
    cin >> binary;
    
    int decimal = binaryToDecimal(binary);
    long long octal = decimalToOctal(decimal);
    
    cout << "Binary: " << binary << " = Octal: " << octal << endl;
    
    return 0;
}
Output
Enter a binary number: 1010
Binary: 1010 = Octal: 12

Understanding Convert Binary to Octal

This program converts binary to octal by first converting to decimal, then to octal. It demonstrates 5 different methods: two-step conversion, direct conversion, using bitset, using string manipulation, and using functions.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents