Dolfaniss, if you need to confirm that the input is in the legal range i.e (0-9, a-f) then there is a function in ctype.h called isxdigit() that you can use it looks for (0-9, a-f, A-F).
You could also use a regex with scanf, or use strtol with argument 16, for hex. This all requires that you use a string as input though. The drawback of strtol alone is that it returns 0, it there was an error, hence you cant tell bogus input apart from 0. If that is necessary you need to first confirm that the string is ok, by, stripping of any newline character, advance the pointer beyond any 0x prefix of the string as isxdigit() does not permit x. then send the string to strtol for conversion to an int.
Example:
Code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
int main(void)
{
char x[11], *xstr; //leaving room for null terminating character and eventual 0x prefix.
int i, num;
bool valid = true;
fgets(x, 11, stdin);
// check if new line char is present, if so, overwrite it with 0.
char *nl = NULL;
nl = strchr(x, '\n');
if(nl)
*nl = 0;
// checking for 0x prefix, if present advance pointer.
xstr = x;
if(!memcmp(xstr, "0x", 2))
xstr += 2;
// confirm that all chars are with in hex num range, if not set flag to false.
for(i = 0; i < strlen(xstr);i++){
if(!(isxdigit(xstr[i])))
valid = false;
}
// if flag is set to false, leave message and exit, else convert string to int.
if(!valid){
puts("bogus input");
return 0;
}
else
num = (int)strtol(xstr, NULL, 16);
printf("0x%x\n", num);
return 0;
}