我撰寫了一個非常簡單的函式來在 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;
}
uj5u.com熱心網友回復:
您可以使用 :
unsigned int val = (unsigned char)bytes[0] << CHAR_BIT;
val |= (unsigned char)bytes[1];
從這個鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/496573.html
上一篇:c中函式中的多指標
