How to convert a number from octal to decimal in C++

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

When we convert an octal number to a decimal number, we multiply each digit of the number by 8n8^n and add the results together.

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

Representation of octal number to decimal equivalent
Conversion of Octal number to Decimal number

The octal number has a base 8 i.e. it ranges from 0-7. The representation of an octal number to its decimal equivalent is shown in the first diagram.

In the second diagram, each digit of the octal number is multiplied by 8n8^n from right to left, with the increasing power of 8n8^n, i.e., 808^0, 818^1, 828^2 and so on. The decimal equivalent of the octal number 123 is 83.

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

#include <iostream>
using namespace std;
int main() {
int decimal = 0, octal, remainder, product = 1;
cin >> octal;
while (octal != 0) {
remainder = octal % 10;
octal = octal / 10;
decimal = decimal + (remainder*product);
product *= 8;
}
cout << "The number in the decimal form is: " << decimal;
return 0;
}

Enter the input below

Explanation

Enter a number above in the input section. The code assumes the number given is an octal number.

  • In line 5, we initialized the variables octal, decimal, remainder, and product.

  • In line 6, we take octal as input.

  • From lines 7 to 12, we initialized a while loop. In the loop, we calculate the remainders and quotients to convert the octal number to its decimal equivalent as discussed in the illustration above .

  • In line 13, we print the output, i.e., the decimal equivalent of the octal number.

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

Free Resources