In this post, we will learn how to convert binary numbers to octal numbers and vice versa using C++ programming language.
Binary to Octal Conversion
To convert a binary number to an octal number, we need to first convert the binary number to a decimal number and then convert the decimal number to an octal number.
To convert a binary number to a decimal number, we can use the following algorithm:
- Initialize the decimal number to zero.
- Multiply the rightmost digit of the binary number by 2^0, the next digit by 2^1, and so on.
- Add the products obtained in step 2 to get the decimal equivalent.
For example, consider the binary number 101101. To convert it to a decimal number, we use the following algorithm:
decimal = 1(2^5) + 0(2^4) + 1(2^3) + 1(2^2) + 0(2^1) + 1(2^0) = 45
Now, to convert the decimal number 45 to an octal number, we can use the following algorithm:
- Divide the decimal number by 8 and store the remainder.
- Repeat step 1 until the quotient becomes zero.
- The octal equivalent is obtained by writing the remainders in reverse order.
For example, to convert the decimal number 45 to an octal number, we use the following algorithm:
45/8 = 5 remainder 5
5/8 = 0 remainder 5
Therefore, the octal equivalent of 45 is 55.
Here’s the C++ code to implement the above algorithm:
#include <iostream> #include <cmath> using namespace std; int main() { long long binary, decimal = 0; int octal = 0, i = 0; cout << "Enter a binary number: "; cin >> binary; // 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; } cout << "The octal equivalent is " << octal << endl; return 0; }
Binary to Octal Conversion
To convert an octal number to a binary number, we need to convert each octal digit to a 3-bit binary number.
For example, consider the octal number 74. To convert it to a binary number, we use the following algorithm:
7 = 111 (in binary)
4 = 100 (in binary)
Therefore, the binary equivalent of 74 is 111100.
Here’s the C++ code to implement the above algorithm:
#include <iostream> #include <cmath> using namespace std; int main() { int octal, decimal = 0, i = 0; long long binary = 0; cout << "Enter an octal number: "; cin >> octal; // Convert octal to decimal while(octal != 0) { decimal += (octal % 10) * pow(8, i); ++i; octal /= 10; } i = 1; // Convert decimal to binary while (decimal != 0) { binary += (decimal % 2) * i; decimal /= 2; i *= 10; } cout << "The binary equivalent is " << binary << endl; return 0; }
In conclusion, we have learned how to convert binary numbers to octal numbers and vice versa using C++ programming language.
The conversion process involves converting a binary number to a decimal number and then converting the decimal number to an octal number or converting an octal number to a binary number by converting each octal digit to a 3-bit binary number.