C program to convert hexadecimal to decimal

Source:www.opentechguides.com | Date Published: 2016-01-06 14:32:46

This is a C program that converts a hexadecimal number to its equivalent decimal number. Apart from the standard C library for I/O functions, the `stdio.h`, this program also requires the header `math.h` which contains several mathematical functions such as ` pow(a,b) ` that returns the value for a to the power of b.

The conversion method used in this program is to multiply each numeral by 16 to the power of that numeral's position and take the sum. For example hexadecimal `2A` is converted to decimal as illustrated below.

 Hex 2 A Value 2 10 Power of 16 161 160 Decimal = Σ 2 * 161 10 * 160 Decimal = 42

The program prompts the user to input a hexadecimal number. The input is validated by checking if the characters are either 0-9 or A-F. Any other character if entered will be ignored by the program.

The program also converts the characters from ASCII to its decimal value.

Program Source Code

```/* **********************************************
* C program to convert Hexadecimal to Decimal	*
************************************************/

#include <stdio.h>
#include <math.h>

int main()
{
int hex[20], dec, i, j, ch, p;

i = 0;
p=0;
dec=0;

printf("Enter a Hexadecimal value : ");
while ((ch=getchar()) != '\n') {
if ((ch > 47 && ch < 58) || (ch > 64 && ch < 71))
hex[i++] = ch;
}

for (j = i-1; j >= 0; j-- ) {
if (hex[j] > 57)
dec +=  (hex[j] - 55) * (int)pow((double)16, p);
else
dec +=  (hex[j] - 48) * (int)pow((double)16, p);

p++;
}

printf("Decimal value is : %d",dec);

//Wait for key press
printf("\n\nPress any key to continue...");
getchar();

return 0;
}```

Sample Output

```
Enter a Hexadecimal value : 2A
Decimal value is : 42

Press any key to continue...
```

Open Tech Guides | www.opentechguides.com