简体   繁体   English

在 C 中安全地将 char* 转换为 unsigned int?

[英]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?我编写了一个非常简单的函数来在 C 中执行这种转换。它完全安全吗? 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这个链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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