Octal to Decimal in C++
We need to write a system that converts octal number into equal decimal number when octal number is given as input.
Let us look at an example of a program in C++ to do so:
// C++ program to convert octal to decimal
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ;
// Function to convert octal to decimal
int octalToDecimalnumber ( int n )
{
int number = n ;
int decimal_value = 0 ;
// Initializing base value to 1, i.e 8 ^ 0
int base_val = 1 ;
int temp = number ;
while ( temp ) {
// extracting last digit
int last_digit = temp % 10 ;
temp = temp / 10 ;
// Multiplying last digit with appropriate
// base value and adding it to decimal_value
decimal_value += last_digit * base ;
base = base * 8 ;
}
return decimal_value ;
}
// Driver program to test above function
int main ( )
{
int number = 33 ;
cout << octalToDecimalnumber ( number ) << endl ;
}
OUTPUT:
27
…..
Process executed in 0.11 seconds
Press any key to continue.
Explanation:
The goal is to subtract the digits of the octal number starting at the far right digit and keep them in a variable called decimal value. Multiply the digit by the correct base (8 Power) and add the variable decimal value when subtracting the octal numerical digits. Finally, the decimal number will be saved on a variable decimal value.
Another example of a program using pre-define function:
// C++ program to convert octal to decimal
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ;
int OctalToDecimal ( string n )
{
return stoi ( n, 0, 8 ) ;
}
int main ( )
{
string n = "33" ;
cout << OctimalToDecimal ( n ) ;
return 0 ;
}
OUTPUT:
27
…..
Process executed in 0.22 seconds
Press any key to continue.
Explanation:
In the above program in C++, we are using stoi function in 7th line of code which takes the octal number and divides it with 8 to convert it into decimal number.