Given an octal number, the task is to convert it into its equivalent decimal value. This can be done manually using powers of 8 or directly using C++'s stoi() function.
- The arithmetic approach processes each octal digit using powers of 8.
- The stoi() approach uses the built-in base-conversion functionality provided by C++.
Examples:
Input : 67
Output: 55Input : 512
Output: 330
Approaches to Convert Octal to Decimal
The conversion can be performed using the following two approaches:
1. Using the Arithmetic Method
The idea is to process the octal number from right to left. Each digit is multiplied by the corresponding power of 8, starting with (8^0), and the results are added to obtain the decimal value.
Steps:
- Initialize decValue to 0 and base to 1, representing (8^0).
- Extract the last digit of the octal number.
- Multiply the digit by the current base and add it to decValue.
- Remove the last digit from the number.
- Multiply base by 8 for the next position.
- Repeat until all digits are processed.
#include <iostream>
using namespace std;
// Function to convert octal to decimal
int octalToDecimal(int n)
{
int decimalValue = 0;
int base = 1; // 8^0
while (n > 0)
{
// Extract the last digit
int lastDigit = n % 10;
// Add digit à current power of 8
decimalValue += lastDigit * base;
// Move to the next power of 8
base *= 8;
// Remove the last digit
n /= 10;
}
return decimalValue;
}
int main()
{
int n = 67;
cout << octalToDecimal(n);
return 0;
}
Output
55
Explanation: For 67, the program first extracts 7 and multiplies it by (8^0). It then extracts 6 and multiplies it by (8^1). Adding these values gives the decimal equivalent 55.
Note: This approach treats the input as an integer. Therefore, it does not preserve leading zeros. For very large octal values, using a string is more appropriate.
2. Using the stoi() Function
C++ provides the stoi() function to convert a string into an integer using a specified number base. By passing 8 as the base, the function interprets the input string as an octal number and returns its decimal equivalent.
#include <iostream>
#include <string>
using namespace std;
// Function to convert octal string to decimal
int octalToDecimal(const string& n)
{
return stoi(n, nullptr, 8);
}
int main()
{
string n = "67";
cout << octalToDecimal(n);
return 0;
}
Output
55
Explanation: The string "67" is passed to stoi() with base 8. The function interprets 67 as an octal number and converts it directly to its decimal value, which is 55.
Note: stoi() returns an int. For values larger than the int range, use stol() or stoll() as appropriate.