Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputing & validating hex values correctly

I'm trying to create a simple program or function that will take the users input which could be a valid hex number.

I'm trying to work out a way to verify that it's a correct hex value and return the hex value if it's true or return an error message if it's false.

I was thinking of a function that checks every char to make sure its 0-9 or A-F but can't think how to implement this.

Thanks.

like image 832
Lemex Avatar asked Nov 29 '22 03:11

Lemex


2 Answers

Given const char *s, if you want to determine if every character in the string pointed to by s is a valid hex digit you can use:

if (s[strspn(s, "0123456789abcdefABCDEF")] == 0)
{
    /* valid */
}
like image 57
caf Avatar answered Dec 06 '22 07:12

caf


Something like this (since you insist it isn't homework, I will fill in):

int CheckMyString(const char *aStr)
{
    const char *curr = aStr;
    while (*curr != 0)
    {
        if (('A' <= *curr && *curr <= 'F') || ('a' <= *curr && *curr <= 'f') || '0' <= *curr && *curr <= '9'))
        {
            ++curr;
        } 
        else 
        {
            return 0;
        }
    }
    return 1;
}
like image 44
drdwilcox Avatar answered Dec 06 '22 08:12

drdwilcox