Problem
How to convert the hexadecimal value to integer value by using the C programming language?
Explain the concept.
Solution
Hexadecimal values represent in 16 symbols 1 to 9 & A to F. Here, A to F decimal equivalent is 10 to 15.
Example
Following is the C program for converting hexadecimal to an integer by using functions −
#include<stdio.h> #include<string.h> #include<math.h> int hextodc(char *hex){ int y = 0; int dec = 0; int x, i; for(i = strlen(hex) - 1 ; i >= 0 ; --i)//{ if(hex[i]>='0'&&hex[i]<='9'){ x = hex[i] - '0'; } else{ x = hex[i] - 'A' + 10; } dec = dec + x * pow(16 , y);// converting hexadecimal to integer value ++y; } return dec; } int main(){ char hex[100]; printf("Enter Hexadecimal: "); scanf("%s", hex); printf("\nDecimal: %d", hextodc(hex)); return 0; }
Output
When the above program is executed, it produces the following result −
1. Enter Hexadecimal: A Decimal: 10 2. Enter Hexadecimal: A12 Decimal: 2578
Explanation
Scan all characters of Hex from Right-To-Left
Let scanned character be A.
Convert A to appropriate decimal form and store it in x.
dec = dec + x * 16y
y= y + 1.
Return decimal.
We can also scan the Hexadecimal value from Left-To-Right but, we must initialize y as y = N – 1 and decrement y on each iteration. N is the length of Hexadecimal.