Related Tags

c++
communitycreator

# How to convert a number from octal to binary in C++

Vinisha Maheshwari

In this shot, we will discuss how to convert a number from octal to binary in C++.

### Octal versus binary

Octal and binary are number systems that represent a number in their respective forms.

An octal number has a base 8 format and uses digits 0 - 7 to represent a number.

A binary number has base 2 format and uses only two digits, 0 & 1, to represent a number.

### Methodology

To convert a number from octal to binary, we will first convert the octal number to a decimal number and then from decimal to binary number.

Let’s see the below image to understand how this conversion works.

Octal to Decimal Conversion
Decimal to Binary Conversion

### Code

We will use the while loop to convert the octal number to its binary equivalent.

As shown in the first image, we will convert octal numbers to decimal ones in the first while loop.

In the second while loop, we will convert the decimal number into its binary equivalent.

Let’s see the code below to understand it in a better way. To run the program, enter any number.

#include <iostream>
#include <math.h>
using namespace std;

int main() {
int decimal = 0, octal, remainder, product = 0;
long binary = 0;

cin >> octal;

while(octal != 0) {
decimal += (octal%10) * pow(8,product);
++product;
octal /= 10;
}

product = 1;
while (decimal != 0) {
binary += (decimal % 2) * product;
decimal /= 2;
product *= 10;
}

cout << "The number in the binary form is: " << binary;
return 0;
}

Enter the input below

Conversion of Octal number to Binary number in C++

### Explanation

• In lines 6 and 7, we initialize the binary, decimal, octal, remainder, and product variables.

• In line 9, we take octal as input.

• From lines 11 to 15, we initialize a while loop. In this loop, we calculate the remainders and quotients discussed in the second illustration (i.e., converting the octal number to its decimal equivalent).

• From lines 18 to 22, we initialize another while loop. In this loop, we calculate the remainders and quotients discussed in the above illustrations (i.e., convert the decimal number to its binary equivalent).

• In line 24, we print the output, i.e., the binary equivalent of the octal number.

In this way, we can convert the value of an octal number to a binary number.

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 