# 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**

- Binary number is taken as input.
- Multiply each digit of the binary number (starting from the last) with the powers of 2 respectively.
- Add all the multiplied digits.
- We get the decimal form, now divide it with 8 and store the remainder.
- Repeat step 4 until number can be divided.
- Print the reverse of the remainder
- We get the octal value

**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;`

`}`