Convert Hexadecimal String to Integer in C programming language.
In this code snippet we will learn how to convert string formatted data into integer using different methods in c programming language.
Code to Convert Hexadecimal String to Integer in C
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
unsigned char text[]="7AF2";
int i,length, intValue,digit,p;
length=strlen(text);
intValue=0;
for(i=(length-1),p=0; i>=0; i--,p++){
if(text[i]>='0' && text[i]<='9'){
digit=text[i]-0x30;
}
else if((text[i]>='A' && text[i]<='F') || (text[i]>='a' && text[i]<='f')){
switch(text[i]) {
case 'A': case 'a': digit=10; break;
case 'B': case 'b': digit=11; break;
case 'C': case 'c': digit=12; break;
case 'D': case 'd': digit=13; break;
case 'E': case 'e': digit=14; break;
case 'F': case 'f': digit=15; break;
}
}
intValue+= digit*pow(16,p);
}
printf("Integer value is: %d\n",intValue);
return 0;
}
Integer value is: 31474