Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Funtion htoi(s) to convert a string of hexadecimal digits into its equivalent
   integer value. The allowable digits are 0 through 9, a
   through f, and A through F. The function returns -1 on encountering
   an invalid character. */


#include <stdio.h>

long htoi(char hex_string[]);

main()
{
	printf( "%ld\n",htoi("ab1"));
}


long htoi(char a[])
{
	char tolower(char a);
	int i=0,d=0;
	while(a[i]!='\0')
		if(a[i]>='0' && a[i]<='9')
			d=d*16+a[i++]-'0';
		else if(tolower(a[i])>='a'&&tolower(a[i])<='f')
			d=d*16+10+tolower(a[i++])-'a';
		else
			return -1;
	return d;
}

char tolower(char a)
{
	if(a>='A'&&a<='Z')
		return a+'a'-'A';
	else
		return a;
}