C - HtoI: Convert a string of hexadecimal digits into its equivalent integer value

Share a big cow's artificial intelligence tutorial. Zero-based! Easy to understand! Funny and humorous! Hope you join the artificial intelligence team too! Please click http://www.captainbed.net

/*
 * Write a function HtoI(s), which converts a string of hexadecimal digits
 * (including an optional 0x or 0X) into its equivalent integer value.
 * The allowable digits are 0 through 9, a through f, and A through F.
 *
 * HtoI.c - by FreeMan
 */

#include <stdio.h>
#include <ctype.h>

unsigned long HtoI(const char s[]);

int main()
{
	printf("%ld\n", HtoI("0xFA9C"));
	printf("%ld\n", HtoI("0xFFFF"));
	printf("%ld\n", HtoI("0X1111"));
	printf("%ld\n", HtoI("0XBCDA"));

	return 0;
}

unsigned long HtoI(const char s[])
{
	unsigned long n = 0;

	for (int i = 0; s[i] != '\0'; i++)
	{
		int c = tolower(s[i]);
		if (c == '0' && tolower(s[i + 1]) == 'x')
		{
			i++;
		}
		else if (c >= '0' && c <= '9')
		{
			n = 16 * n + (c - '0');
		}
		else if (c >= 'a' && c <= 'f')
		{
			n = 16 * n + (c - 'a' + 10);
		}
	}

	return n;
}

// Output:
/*
64156
65535
4369
48346

*/

 

Guess you like

Origin blog.csdn.net/chimomo/article/details/113566119