C++ Program to convert binary to octal
Program
#include<iostream>
#include<math.h>
using namespace std;
int binary_octal(long long binary)
{
int octal = 0, decimal = 0, i = 0;
// convert binary to decimal
while(binary != 0)
{
decimal += (binary%10) * pow(2,i);
++i;
binary/=10;
}
i = 1;
// convert decimal to octal
while (decimal != 0) {
octal += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}
return octal;
}
int main() {
long long binary;
cout << "Enter a binary number: ";
cin >> binary;
cout << "Octal equivalent is: " << binary_octal(binary);
return 0;
}
Output
$ g++ convert-binary-to-octal.cpp
$ ./a.out
Enter a binary number: 11100011
Octal equivalent is: 343