Home > Software engineering >  Converting a char* to unsigned int in C safely?
Converting a char* to unsigned int in C safely?

Time:06-24

I wrote a pretty simple function to perform this conversion in C. Is it perfectly safe? if not, what are the other ways?

EDIT: I rewrote the function to add more effective error checks.

#define UNLESS(x) if (!(x))

int char_to_uint(const char *str, unsigned int* res)
{    
    /* return 0 if str is NULL */
    if (!str){
        return 0;
    }

    char *buff_temp;
    long long_str;

    /* we set up errno to 0 before */
    errno = 0;

    long_str = strtol(str, &buff_temp, 10); 

    /* some error and boundaries checks */
    if (buff_temp == str || *buff_temp != '\0' || long_str < 0){
        return 0; 
    }

    /* errno != 0 = an error occured */
    if ((long_str == 0 && errno != 0) || errno == ERANGE){
        return 0;
    }

    /* if UINT_MAX < ULONG_MAX so we check for overflow */
    UNLESS(UINT_MAX == ULONG_MAX){
        if (long_str > UINT_MAX) {
            return 0;
        } else {
            /* 0xFFFFFFFF : real UINT_MAX */
            if(long_str > 0xFFFFFFFF){ 
                return 0;
            } 
        }  
    }

    /* after that, the cast is safe */
    *res = (unsigned int)long_str;

    return 1;
}

CodePudding user response:

You can use :

unsigned int val = (unsigned char)bytes[0] << CHAR_BIT;
val |= (unsigned char)bytes[1];

from this link

  • Related