# Binary to Octal Conversion

Binary to Octal Conversion” is one of the classic programming problem for beginners. Here, we are given a Binary Number, entered by user and our task is to write a program to convert the given binary number to its equivalent octal number.

Example (Binary to Octal Conversion):

```Binary = 100011011
Octal = 433```

The steps required for Binary to Octal Conversion are as follows:

1. Make sure the number of digits in binary number is divisible by 3. If not, add extra 0s in front.
2. Divide the binary number into pairs of 3-digit binary number.
3. Convert each 3-digit binary number pair to its decimal form.
4. Combine all the decimal numbers and store into ‘Octal’.
5. Print the result.

#### C++ Program for Binary to Octal Conversion is as follows:

```/* C++ Program for Binary to Octal Conversion Number*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan the Binary Number */
string Binary;
cout<<"Enter the Binary Number: ";
cin>>Binary;

/* Converting Binary to Octal*/

/* Make sure the number of digits in 'Binary'
Number is divisible by 3. If not, add
required 0s in front*/
while(Binary.length() % 3 != 0)
{
Binary.insert(0,"0");
}

/* Converting each digit of Binary number
into 3-digit binary number pair and convert
each pair to its corresponding decimal
*/
string Octal = "";
for(int i = 0; i < Binary.length(); i=i+3)
{
string temp;
temp = temp + Binary[i];
temp = temp + Binary[i+1];
temp = temp + Binary[i+2];
if(temp == "000")
Octal += '0';
else if(temp == "001")
Octal += '1';
else if(temp == "010")
Octal += '2';
else if(temp == "011")
Octal += '3';
else if(temp == "100")
Octal += '4';
else if(temp == "101")
Octal += '5';
else if(temp == "110")
Octal += '6';
else if(temp == "111")
Octal += '7';
}

/*Printing the result */
cout<<"The Octal of "<<Binary<<" is "<<Octal;
}

```
```OUTPUT:
Enter the Binary Number: 100011011
The Octal of 100011011 is 433```

Related Posts: