将char*转换为c安全中的unsigned int?
我写了一个非常简单的功能来在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用:
来自此链接
You can use :
from this link