简体   繁体   中英

Converting a char* to unsigned int in C safely?

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;
}

You can use :

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

from this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM