Convert Binary to Octal program in C++
Written by
Convert Binary to Octal program
Given: Binary number as input and we have to convert it to octal number.
This can be done by multiplying each digit of binary number starting from LSB with powers of 2 respectively, converting it to decimal and then diving it with 8 until it can be divided and print the reverse of remainder to get the octal value.
Example:
Binary number: 100101
(1*2^5) + (0*2^4)+ (0*2^3)+ (1*2^2)+ (0*2^1)+ (1*2^0) = 37
Decimal number =37
Divide 37 successively by 8 until the remainder is 0
37/8 = 4, remainder is 5
4/8 = 0, remainder is 4
Read from the bottom (MSB) to top (LSB) as 45
Octal number = 45
# Algorithm
- Prompt the user to enter a binary number.
- Iterate over the binary number from the least significant digit to the most significant digit, using a loop.
- For each digit, multiply it by the corresponding power of 2 (using the counter variable as the exponent) and add the result to the overall result.
- Divide the result by 8 and store the remainder.
- Repeat step 5 until the result is 0.
- Print the octal representation of the binary number by printing the remainder digits in reverse order.
Code:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
// as binary numbers can be long
long binary, binaryinput;
int remainder, decimal_output, quotient, i, j, octal_output[100];
cout << "Enter a binary number: ";
cin >> binaryinput;
binary = binaryinput;
i = 1;
decimal_output = 0;
// converting binary input to decimal
while (binaryinput > 0) {
remainder = binaryinput % 10;
decimal_output = decimal_output + remainder * i;
i = i + i;
binaryinput = binaryinput / 10;
}
i = 1;
// converting decimal to octal
quotient = decimal_output;
while (quotient > 0) {
octal_output[i++] = quotient % 8;
quotient = quotient / 8;
}
// printing the output
cout << "The equivalent octal value of binary number " << binary << " is: ";
for (j = i - 1; j > 0; j--) {
cout << octal_output[j];
}
return 0;
}
Output
Enter a binary number: 1010101
The equivalent octal value of binary number 1010101 is: 125