Convert Binary to Octal program in C++

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

  1. Binary number is taken as input.
  2.  Multiply each digit of the binary number (starting from the last) with the powers of 2 respectively.
  3.  Add all the multiplied digits.
  4.  We get the decimal form, now divide it with 8 and store the remainder.
  5. Repeat step 4 until number can be divided.
  6. Print the reverse of the remainder
  7. 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 &lt;&lt; " Enter a binary number : ";
cin &gt;&gt; binaryinput;
binary = binaryinput;
i = 1;
decimal_output = 0;

//converting binary input to decimal

while (binaryinput &gt; 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 &gt; 0)

{

	octal_output[i++] = quotient % 8;

	quotient = quotient / 8;
}

//printing the output

cout &lt;&lt; " The equivalent octal value of binary number " &lt;&lt; binary &lt;&lt; " is : ";

for (j = i - 1; j &gt; 0; j--)

{

	cout &lt;&lt; octal_output[j];
}

return 0;

}