Program for Binary to Octal Conversion in C++
Binary to Octal Conversion
Converting a binary number to octal involves grouping binary digits into sets of three from right to left and converting each set to its octal equivalent.
We will explore three methods to perform this conversion using C++ programming.
Method 1: Using Built-in Function
We first convert the binary number to decimal and then use the built-in function to convert it to octal.
#include#include using namespace std; int binaryToDecimal(long long n) { int decimal = 0, base = 1; while (n > 0) { decimal += (n % 10) * base; n /= 10; base *= 2; } return decimal; } int main() { long long binary; cout << "Enter a binary number: "; cin >> binary; cout << "Octal: " << oct << binaryToDecimal(binary) << endl; return 0; }
Output:
Enter a binary number: 101010 Octal: 52
Method 2: Using Division by 8
We convert binary to decimal and then repeatedly divide the decimal number by 8 to get the octal equivalent.
#include#include using namespace std; void decimalToOctal(int decimal) { vector octal; while (decimal > 0) { octal.push_back(decimal % 8); decimal /= 8; } for (int i = octal.size() - 1; i >= 0; i--) { cout << octal[i]; } cout << endl; } int binaryToDecimal(long long n) { int decimal = 0, base = 1; while (n > 0) { decimal += (n % 10) * base; n /= 10; base *= 2; } return decimal; } int main() { long long binary; cout << "Enter a binary number: "; cin >> binary; decimalToOctal(binaryToDecimal(binary)); return 0; }
Output:
Enter a binary number: 101010 Octal: 52
Method 3: Using Recursion
We use recursion to first convert binary to decimal and then recursively convert decimal to octal.
#includeusing namespace std; int binaryToDecimal(long long n) { if (n == 0) return 0; return (n % 10) + 2 * binaryToDecimal(n / 10); } void decimalToOctalRecursive(int n) { if (n == 0) return; decimalToOctalRecursive(n / 8); cout << (n % 8); } int main() { long long binary; cout << "Enter a binary number: "; cin >> binary; int decimal = binaryToDecimal(binary); if (decimal == 0) cout << "0"; else decimalToOctalRecursive(decimal); cout << endl; return 0; }
Output:
Enter a binary number: 101010 Octal: 52