K&R C Exercise 2-3 Solution

/*
 * Exercise 2-3 Write the function htoi(s), which converts a string
 * of hexadecimal digits into its equivalent integer value.
 */
#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 10

int is_valid_hex_alpha( int c );
int htoi( char s[] );

int main()
{
	int c, i;
	
	char s[MAX_LEN] = { '\0' };
	i = 0;
	
	while( ( c = getchar() ) != EOF )
	{
		if( is_valid_hex_alpha( c ) )
		{
			s[i++] = c;		
		}
		else if( c == '\n' )
		{
			printf( "%d\n", htoi( s ) );
			i = 0;
		}
	}

	return 0;
}

int is_valid_hex_alpha( int c )
{
	return isdigit( c ) || ( c >= 'a' && c <= 'f' ) || ( c >= 'A' && c <= 'F' );
}

int htoi( char s[] )
{
	int n, i;
	for( i = n = 0; is_valid_hex_alpha( s[i] ); ++i )
	{
		if( s[i] == '0' || s[i] == 'x' )
			continue;
		else
		{
			if( s[i] >= '0' && s[i] <= '9' )
				n = n * 16 + s[i] - '0';
			else if( islower( s[i] ) )
				n = n * 16 + 10 + ( s[i] - 'a' );
			else
				n = n * 16 + 10 + ( s[i] - 'A' );
		}
	}
	return n;
}

你可能感兴趣的:(K&R C Exercise 2-3 Solution)