How to convert octal to decimal?
Octal value 756
(7 X 8^2) + (5 X 8^1) + (6 X 8^0) = (7 X 64) + (5 X 8) + 6 = 494
Multiply each digit with their corresponding power of 8 and calculate the sum of all.
Write a C program to convert octal number to decimal number
Octal value 756
(7 X 8^2) + (5 X 8^1) + (6 X 8^0) = (7 X 64) + (5 X 8) + 6 = 494
Multiply each digit with their corresponding power of 8 and calculate the sum of all.
Write a C program to convert octal number to decimal number
#include <math.h>
#include <string.h>
int main () {
char data[10], ch;
int val = 0, power = 0, i = 0, j = 0;
/* get the octal input from the user */
printf("Enter your octal value:");
fgets(data, 10, stdin);
data[strlen(data) - 1] = '\0';
/* convert octal to decimal value */
for (i = strlen(data); i > 0; i--) {
ch = data[j++];
power = pow(8, i - 1);
if (ch >='0'&& ch <= '7') {
/* octal to decimal conversion */
val = val + (ch - '0') * power;
} else {
/* value other than 0-7 are invalid */
printf("Wrong Input!!!\n");
return (-1);
}
}
/* print the result */
printf("Equivalent Decimal Value: %d\n", val);
return 0;
}
Note:
gcc oct2dec.c -lm => link math library since we have used pow() function.
Output:
jp@jp-VirtualBox:~/$ gcc oct2dec.c -lm
jp@jp-VirtualBox:~/$ ./a.out
Enter your octal value:756
Equivalent Decimal Value: 494
jp@jp-VirtualBox:~/$ ./a.out
Enter your octal value:756
Equivalent Decimal Value: 494
No comments:
Post a Comment