Octal to Decimal Conversion in C
Octal to Decimal Conversion
Octal to Decimal conversion is the process of converting an octal number (base-8) into its equivalent decimal number (base-10). Each octal digit represents a power of 8.
For example, the octal number 17 is equal to decimal 15 because:
(1 × 8¹) + (7 × 8⁰) = 8 + 7 = 15
We will explore three methods to convert an octal number to a decimal number using C programming.
Method 1: Using Loop
We extract each digit of the octal number, multiply it by the corresponding power of 8, and sum the results.
#include <stdio.h>
#include <math.h>
int octalToDecimal(long long octal) {
int decimal = 0, i = 0;
while (octal != 0) {
int lastDigit = octal % 10;
decimal += lastDigit * pow(8, i);
octal /= 10;
i++;
}
return decimal;
}
int main() {
long long octal;
printf("Enter an octal number: ");
scanf("%lld", &octal);
printf("Decimal equivalent: %d", octalToDecimal(octal));
return 0;
}
Output:
Enter an octal number: 17 Decimal equivalent: 15
Method 2: Using Built-in Function
We can use sscanf() to directly convert an octal number to a decimal number.
#include <stdio.h>
int main() {
int decimal;
char octal[20];
printf("Enter an octal number: ");
scanf("%s", octal);
sscanf(octal, "%o", &decimal);
printf("Decimal equivalent: %d", decimal);
return 0;
}
Output:
Enter an octal number: 17 Decimal equivalent: 15
Method 3: Using Recursion
We recursively extract each digit and multiply it by the corresponding power of 8.
#include <stdio.h>
#include <math.h>
int octalToDecimalRecursive(long long octal, int power) {
if (octal == 0)
return 0;
return (octal % 10) * pow(8, power) + octalToDecimalRecursive(octal / 10, power + 1);
}
int main() {
long long octal;
printf("Enter an octal number: ");
scanf("%lld", &octal);
printf("Decimal equivalent: %d", octalToDecimalRecursive(octal, 0));
return 0;
}
Output:
Enter an octal number: 17 Decimal equivalent: 15