In this tutorial, we will write a C++ program to convert a binary number into octal using while loop. Before that, you must have knowledge of the following topics in C++.
Binary number
The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.
Octal number
The octal numbers are the numbers with base 8 and use the digits 0 to 7. Example: 8 in decimal is represented as 10 in octal, 25 as 31, and so on.
Let us go through a program for the Binary to Octal Conversion in C++.
C++ Program to Convert Binary to Octal
#include <iostream>
#include <cmath>
using namespace std;
//user defined function
int conversionFunc(int binNumber)
{
int octNumber = 0, deciNum = 0, i = 0;
while (binNumber != 0)
{
deciNum += (binNumber % 10) *pow(2, i);
++i;
binNumber /= 10;
}
i = 1;
while (deciNum != 0)
{
octNumber += (deciNum % 8) *i;
deciNum /= 8;
i *= 10;
}
return octNumber;
}
// MAIN Function
int main()
{
int binNumber, result;
cout << "Enter a binary number: ";
cin >> binNumber;
result = conversionFunc(binNumber);
cout << "Equivalent Octal value: " << result;
return 0;
}
Output:
Enter a binary number: 1101110
Equivalent Octal value: 156
You may go through the vice versa conversion: