C++ Program to Convert Octal Number to Binary Number


In a computer system, the binary number is expressed in the binary numeral system while the octal number is in the octal numeral system. The binary number is in base 2 while the octal number is in base 8.

Examples of binary numbers and their corresponding octal numbers are as follows −

Binary NumberOctal Number
0110115
001015
1011026
0101012

A program that converts the octal numbers into binary is given as follows −

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int OctalToBinary(int octalNum) {
   int decimalNum = 0, binaryNum = 0, count = 0;

   while(octalNum != 0) {
      decimalNum += (octalNum%10) * pow(8,count);
      ++count;
      octalNum/=10;
   }
   count = 1;
   while (decimalNum != 0) {
      binaryNum += (decimalNum % 2) * count;
      decimalNum /= 2;
      count *= 10;
   }
   return binaryNum;
}
int main() {
   int octalNum = 33;
   cout <<"Octal to Binary"<<endl;
   cout<<"Octal number: "<<octalNum<<endl;
   cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl;
   return 0;
}

Output

The output of the above program is as follows −

Octal to Binary
Octal number: 33
Binary number: 11011

In the given program, the function OctalToBinary() converts the given octal number into a binary number This is done by first converting the octal number into a decimal number and then converting the decimal number into an binary number. This is seen in the following code snippet −

int OctalToBinary(int octalNum) {
   int decimalNum = 0, binaryNum = 0, count = 0;
   while(octalNum != 0) {
      decimalNum += (octalNum%10) * pow(8,count);
      ++count;
      octalNum/=10;
   }
   count = 1;
   while (decimalNum != 0) {
      binaryNum += (decimalNum % 2) * count;
      decimalNum /= 2;
      count *= 10;
   }
   return binaryNum;
}

In the function main(), the octal number is given. Then its corresponding binary number is calculated by calling OctalToBinary(). This is shown below −

int main() {
   int octalNum = 33;
   cout <<"Octal to Binary"<<endl;
   cout<<"Octal number: "<<octalNum<<endl;
   cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl;
   return 0;
}

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements