Ask Your Question
1

What is the method to verify that a char* only consists of hexadecimal characters in C?

asked 2021-08-06 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-05 05:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-06 11:00:00 +0000

Seen: 12 times

Last updated: Mar 05 '22