Don't worry about the functions in the scanf family. They are almost impossible to use sensibly. Here is the general safe use of strtoull :
char *str, *end; unsigned long long result; errno = 0; result = strtoull(str, &end, 16); if (result == 0 && end == str) { } else if (result == ULLONG_MAX && errno) { } else if (*end) { }
Note that strtoull accepts the optional 0x prefix in the string, as well as the optional leading spaces and sign ( + or - ). If you want to reject them, you must run the test before calling strtoull , for example:
if (!isxdigit(str[0]) || (str[1] && !isxdigit(str[1])))
If you also want to prohibit too long representations of numbers (leading zeros), you can check the following condition before calling strtoull :
if (str[0]=='0' && str[1])
Another thing to keep in mind is that "negative numbers" are not counted outside the conversion range; instead, the prefix - treated in the same way as the unary negation operator in C, applied to an unsigned value, therefore, for example, strtoull("-2", 0, 16) will return ULLONG_MAX-1 (without setting errno ).
R ..
source share