Related Tags

c++
communitycreator

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

Vinisha Maheshwari

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

When we convert a binary number to an octal number, we divide the binary number by taking three digits from the right side of the binary number and then multiplying each digit by ($2^n$). If, for the left-most part, there are less than three digits left, we add extra zeros to the left of the binary number to make three in total.

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

Binary to octal conversion

In the image above, the binary number is multiplied by $2^n$ ​starting from the right side, with the increasing power of $n$ in the same direction. We will divide the binary number into sets of three numbers from right to left. In this case, there are less than three digits in the left-most part, so, we add 0 to the left of that value, as shown in the image above. The value of binary number 11001 in octal form is 31.

## Code

Let’s look at the below code snippet to understand this better.

#include <iostream>
using namespace std;

int main() {
int binnum1, binary, rem, decnum = 0, quot, i = 1, j;
int octnum;
cin>> binary;

binnum1 = binary;
while(binary > 0)
{
rem = binary % 10;
decnum = decnum + rem * i;
i = i * 2;
binary = binary/10;
}
i=1;
quot = decnum;
while(quot > 0)
{
octnum[i++] = quot % 8;
quot = quot / 8;
}

cout<<" The equivalent octal value of " <<binnum1<< " is : ";
for(j = i - 1; j > 0; j--)
cout<<octnum[j];

return 0;
}

Enter the input below

Conversion of a binary number to an octal number in C++

Enter a binary number above in the input section.

### Explanation

• In lines 5 and 6, we initialize the variables octnum, i, j, decnum, binnum1, quot, rem, and binary.

• In line 7, we take binary as input.

• From lines 10 to 23, we initialize a while loop. In the loop, we calculate the remainders and quotients, as we discussed in the above illustration, to convert the binary number to its octal equivalent.

• In line 25, we print the output, i.e., the hexadecimal equivalent of the binary number.

• From lines 26 to 27, we initialize a for loop where we have created conditions to print the binary number to its octal equivalent.

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 