Mic*_*ine 7 c type-conversion uint64
我试过了
sscanf(str, "%016llX", &int64 );
Run Code Online (Sandbox Code Playgroud)
但似乎不安全.是否有快速安全的方式进行型式铸造?
谢谢〜
不要打扰scanf家庭中的功能.它们几乎不可能强有力地使用.以下是一般安全使用strtoull:
char *str, *end;
unsigned long long result;
errno = 0;
result = strtoull(str, &end, 16);
if (result == 0 && end == str) {
/* str was not a number */
} else if (result == ULLONG_MAX && errno) {
/* the value of str does not fit in unsigned long long */
} else if (*end) {
/* str began with a number but has junk left over at the end */
}
Run Code Online (Sandbox Code Playgroud)
请注意,在字符串上strtoull接受可选0x前缀,以及可选的初始空格和符号字符(+或-).如果要拒绝这些,则应在调用之前执行测试strtoull,例如:
if (!isxdigit(str[0]) || (str[1] && !isxdigit(str[1])))
Run Code Online (Sandbox Code Playgroud)
如果您还希望禁止过长的数字表示(前导零),您可以在调用之前检查以下条件strtoull:
if (str[0]=='0' && str[1])
Run Code Online (Sandbox Code Playgroud)
还要记住的另一件事是"负数"不被视为超出转换范围; 相反,前缀的-处理方式与C中应用于无符号值的一元否定运算符相同,因此例如strtoull("-2", 0, 16)将返回ULLONG_MAX-1(不设置errno).