C Program to Convert Hexadecimal to Decimal

Write a Program to Convert Hexadecimal to Decimal in C. Input Hexadecimal Number as string.

Example,

Input: A2
Output: 162

Input: 2FC
Output: 764

How to Convert from Hexadecimal to Decimal

Suppose,

\bf Hexadecimal\;Number = a_n  a_{n-1}  \ldots a_{2} a_{1} a_{0}\; of\; n  \; digits

The corresponding decimal number is given by

\bf\\*Decimal\; Number = a_n *16^{n} + a_{n-1} *16^{n-1} +  \ldots +a_2 *16^{2}+a_1 *16^{1}+a_0 *16^{0}

Algorithm

Steps

Let Hex be the input string.

  1. Initialize p = 0, decimal = 0.
  2. Scan all characters of Hex and perform the following operations from Right-To-Left
    1. Let scanned character be ch.
    2. Convert ch to appropriate decimal form and store it in r.
    3. decimal = decimal + r * 16p
    • p= p + 1.
  3. Return decimal.

Note: We can also scan Hex from Left-To-Right but in that case, we must initialize p as p = N – 1 and decrement p on each iteration. N is the length of Hex.

Program to Convert Hexadecimal to Decimal in C

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

int HexadecimalToDecimal(char *hex) {
	int p = 0; 
	int decimal = 0;
	int r, i;
	
	// instead of reading charcacters from Right-To-Left
	// we can also read character from Left-To-Right
	// we just have to initialize p with strlen(c) - 1
	// and decrement p in each iteration
	for(i = strlen(hex) - 1 ; i >= 0 ; --i){
		
		// converting c[i] to appropriate decimal form
		if(hex[i]>='0'&&hex[i]<='9'){
			r = hex[i] - '0';
		}
		else{
			r = hex[i] - 'A' + 10;
		}
		
		decimal = decimal + r * pow(16 , p);
		++p;
	}
	
	return decimal;
}

int main() {

	char hex[100];
	printf("Enter Hexadecimal: ");
	scanf("%s", hex);
	printf("\nDecimal: %d", HexadecimalToDecimal(hex));
	return 0;

}

Output

hexadecimal to decimal

What to study next?

  1. Octal to Decimal

References

https://simple.wikipedia.org/wiki/Hexadecimal

Leave a Comment

Your email address will not be published. Required fields are marked *