将char*转换为c安全中的unsigned int?

发布于 2025-02-10 10:50:41 字数 1123 浏览 1 评论 0原文

我写了一个非常简单的功能来在C中执行此转换。它是否完全安全?如果没有,其他方法是什么?

编辑: 我重写该功能以添加更有效的错误检查。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

離殇 2025-02-17 10:50:41

您可以使用:

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

来自此链接

You can use :

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

from this link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文