*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.

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

**p= p + 1**.

- Let scanned character be
- 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

*What to study next?*

## References

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