Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One possible method is to use a loop to iterate through each character in the string and check if it is a valid hexadecimal character using the following condition:

if (!isxdigit(str[i])) {
    // invalid character found
    break;
}

Here, the isxdigit() function checks if a character is a hexadecimal digit (0-9,A-F,a-f). If an invalid character is found, the loop can be terminated early and a flag can be set to indicate a validation error.

Alternatively, you could use the strtol() function to attempt to convert the string to a long integer using base 16 (hexadecimal). If the entire string is valid, this should succeed without any errors. Here's an example:

char* str = "abcdef123456";
char* endptr;
long val = strtol(str, &endptr, 16);
if (*endptr != '\0') {
    // invalid characters found
}

In this code, strtol() converts the string str to a long integer using base 16 (hexadecimal). The endptr parameter is set to point to the first invalid character in the string, if any. If endptr is not pointing to the null terminator at the end of the string, then there were invalid characters in the string.