Convert a string of hexadecimal digits into its equivalent integer values in C (can use atoi)



Problem : Write a function htoi(s) which converts a string of hexadecimal digits(including optional 0X) into its equivalent integer value.The allowable digits are 0 to 9, a through f.

I suggest a simple solution of this problem.

Take a character array to store the hexadecimal number.Declare a character pointer to this array that points to the first element initially.In case '0' or 'X' is encountered then increment the pointer to point to 3rd and 4th character.Make seperate cases to handle 'a','b','c','d','e','f' or 'A ,'B' ,'C','D','E','F' with respective integer values.The default case outputs the numeric value of the character (sored in c here).

# include <stdio.h>

main()

{

char str[10];

char *ptr,c;

int icount;

int sum=0;

printf ("\n Enter the hexadecimal number with initials as 0X");

scanf("%s",str) ;

ptr=str;

printf("\n You entered : %s \n", ptr) ;

while(*ptr != '\0' );

{

c=*ptr;

if (c=='0' && (*(ptr+1))='X')

p=p+2 ;

c=*ptr++ ;

switch(c)

{

case 'a' : icount=10; break

case 'b' : icount=11; break

case 'c' : icount=10; break

case 'd' : icount=11; break

case 'e' : icount=10; break

case 'f' : icount=11; break

default:

icount=(int)(c) - (int)('0') ;

}

sum=16*sum + i ;

}

printf("%s=%d\n",str,sum);

}