C program to convert hexadecimal to decimal

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.

Hex2A
Value210
Power of 16161160
Decimal = Σ2 * 16110 * 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;

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

   // Convert Hexadecimal to Decimal
 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++;
 }

 // Print the hexadecimal value
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...

Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.