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 $8^n$ and add the results together.
Let’s look at the image below to understand how this conversion works.
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 $8^n$ from right to left, with the increasing power of $8^n$, i.e., $8^0$, $8^1$, $8^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
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.
RELATED TAGS
CONTRIBUTOR
View all Courses