C++ Program for Binary to Octal conversion

Program for Binary to Octal conversion

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

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

  • grouping the binary number into pairs of three and converting into octal.
  • By converting the binary number into a decimal number first and then convert that decimal number into an octal number.

We are using second approach, this approach is long but it is very easy to implement and also the chances of error are also very minimum.

Example:10110

Decimal number     =    1*(2^4) + 0*(2^3) + 1*(2^2) + 1*(2^1) + 0*(2^0)

=    16 + 0 + 4 + 2 + 0

=    22

Octal conversion    →     22/8, Remainder = 6, Quotient = 2

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

i.e 10110 in binary is 26 in octal.

program to convert binary to octal

Working

Let’s see how the code works:

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

            rem = binary %10;

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

    int res = rem*pow(2,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 an octal number.
      • The number is divided by 8 and the remainder is stored.

   rem = decimal % 8;

      • The octal number is constructed using the remainder.

   octal += rem * i;

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

   while (decimal != 0)

  • octal is returned and printed as output.

C++ Code

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

Output

Enter a binary number: 10101
10101 in binary = 25 in octal

Please Login/Signup to comment