Write a program that reads a string and interprets it as a positive integer in the hexadecimal base. For the conversion, use the functions of <ctype.h> and the alphabetic precedence of the characters. The conversion ignores characters that do not represent a hexadecimal digit and stops at the end of the string. The result will be stored in a variable of type long and displayed in the hexadecimal and decimal bases.


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
main()
{
	/* Declarations */
	char CH[100]; /* numerical string to convert */
	long N; /* numerical result */
	int I;  /* counter */
	int OK; /* logical flag indicating whether the */
			/* string was converted successfully */

	/* Reading */
	printf("Enter a positive hexadecimal integer number : ");
	gets(CH);
	/* Conversion of the string */
	OK = 1;
	N = 0;
	for (I = 0; OK && CH[I]; I++)
		if (isxdigit(CH[I]))
		{
			CH[I] = toupper(CH[I]);
			if (isdigit(CH[I]))
				N = N * 16 + (CH[I] - '0');
			else
				N = N * 16 + 10 + (CH[I] - 'A');
		}
		else
			OK = 0;

	/* dislay */
	if (OK)
	{
		printf("Numerical Hexadecimal Value : %lX\n", N);
		printf("Numerical Decimal Value     : %ld\n", N);
	}
	else
		printf("\a\"%s\" does not represent a correct "
			"positive hexadecimal integer number.\n", CH);
	getch();

}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Heap of prime factors