#include <iostream>
#include <cmath>
using namespace std;
int main() {
long long octal;
int decimal = 0, i = 0, remainder;
cout << "Enter an octal number: ";
cin >> octal;
long long temp = octal;
while (temp != 0) {
remainder = temp % 10;
temp /= 10;
decimal += remainder * pow(8, i);
++i;
}
cout << "Octal: " << octal << " = Decimal: " << decimal << endl;
return 0;
}Output
Enter an octal number: 12 Octal: 12 = Decimal: 10
Convert Octal to Decimal in C++
This program teaches you how to convert an octal number to its decimal (base-10) equivalent in C++. Octal is a base-8 number system that uses digits 0-7. While less common than binary or decimal, octal is still used in some computing contexts, especially for file permissions in Unix/Linux systems. Understanding octal conversion helps you work with different number systems.
What This Program Does
The program converts an octal number (base-8) to a decimal number (base-10). For example:
- Input octal: 12
- Output decimal: 10
Octal numbers use digits 0-7, while decimal numbers use digits 0-9. The conversion involves multiplying each octal digit by 8 raised to its position power and summing the results.
Example:
- 12 (octal) = 1×8¹ + 2×8⁰ = 8 + 2 = 10 (decimal)
- 145 (octal) = 1×8² + 4×8¹ + 5×8⁰ = 64 + 32 + 5 = 101 (decimal)
Algorithm
The conversion uses a while loop:
cppwhile (temp != 0) { remainder = temp % 10; temp /= 10; decimal += remainder * pow(8, i); ++i; }
Step-by-step for octal = 12:
- Extract rightmost digit: 12 % 10 = 2, decimal = 0 + 2×8⁰ = 2
- Remove digit: 12 / 10 = 1
- Extract digit: 1 % 10 = 1, decimal = 2 + 1×8¹ = 10
- Final result: decimal = 10
Understanding Octal System
Positional Value System:
In octal, each position represents a power of 8:
- Position 0 (rightmost): 8⁰ = 1
- Position 1: 8¹ = 8
- Position 2: 8² = 64
- Position 3: 8³ = 512
Valid Octal Digits:
- Octal uses only digits 0, 1, 2, 3, 4, 5, 6, 7
- Digits 8 and 9 are not valid in octal
Why Octal?:
- Historically used in computing (easier to read than binary)
- Still used for file permissions in Unix/Linux (e.g., chmod 755)
- Groups of 3 binary digits correspond to 1 octal digit
Summary
- Octal-to-decimal conversion multiplies each digit by 8^position and sums the results.
- Octal is base-8 (uses digits 0-7), decimal is base-10 (uses digits 0-9).
- The algorithm processes digits from right to left (least significant to most significant).
- Understanding octal is useful for file permissions and system administration.
This program is essential for understanding number systems, file permissions, and system administration tasks.