C++ Program for Octal to Binary conversion

Program for Octal to Binary conversion

Here we will discuss how to convert an octal number into a binary number using C++ programming language.

There are many approaches of converting an octal number into a binary number like:

  • Break the number into individual digits and then convert the corresponding digits into binary. 
  • By converting the octal number into a decimal number first and then convert that decimal number into a binary number.

We are using the second approach, it is a long but very simple approach which can also be implemented easily with minimum chances of error.

Example: 26

Decimal number         = 2*(8^1) + 6*(8^0)

            = 16 + 6

            = 22

Binary conversion    →     22/2, Remainder = 0, Quotient =11

  →     11/2, Remainder = 1, Quotient = 5

  →     5/2, Remainder = 1, Quotient = 2

  →     2/2, Remainder = 0, Quotient = 1

  →     1/2, Remainder = 1, Quotient = 0

i.e 26 in octal is 10110 in binary.

Program to convert octal to binary

Working

Let’s see how the code works:

  • User gives an input(octal number).
  • Input is stored in an int type variable say octal.
  • A function convert() is called using octal as parameter.
    • A loop is started to convert octal into a decimal number
      • Digits of octal are extracted one by one starting from right.

            int rem = octal%10;

      • Extracted digits are multiplied with proper base i.e. power of 8.

    int res = rem*pow(8,i);

      • After multiplying each digit with proper base the results are added and stored in another variable say decimal.

    decimal += res;

    • Another loop is started to convert decimal into a binary number 
      • The number is divided by 2 and the remainder is stored.

    rem = decimal%2;

      • The binary number is constructed using the remainder.

            binary += rem*i;

      • The loop will run until the number is not equal to 0.

             while (n!=0)

  • binary is returned and printed as output.

C++ Code

//C++ Program
// Octal to Binary conversion
#include <iostream>
#include <math.h>
using namespace std;
//Function to convert octal to binary
long convert(int octal)
{
int decimal = 0, i = 0;
long binary = 0;
//converting octal to decimal
while(octal != 0)
{
int rem = octal%10;
int res=rem * pow(8,i);
decimal += res;
i++;
octal/=10;
}
i = 1;
//converting decimal to binary
while (decimal != 0)
{
int rem = decimal % 2;
binary += rem * i;
decimal /= 2;
i *= 10;
}
return binary;
}
//main program
int main()
{
int octal;
cout << "Enter an octal number: ";
//user input
cin >> octal;
//function call
long binary = convert(octal);
//printing output
cout << octal << " in octal = " << binary << " in binary";
return 0;
}

Output

Enter an octal number: 307
307 in octal = 11000111 in binary

Please Login/Signup to comment