# 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, The corresponding decimal number is given by ## 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 p = 0;
int decimal = 0;
int r, i;

// 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;
scanf("%s", hex);
}