C++标准库是否有32位补码十六进制字符串转十进制的函数?
C++标准库实现十六进制字符串转带符号十进制整数
C++标准库没有直接提供和示例中hex_to_int完全对应的函数,但可以通过标准库中的字符串转换工具组合实现需求,以下是两种可靠的实现方式:
方法一:使用std::strtol
std::strtol可以将十六进制字符串转换为long类型,再通过类型转换得到目标int值:
#include <cstdlib> #include <string> #include <cstdio> int main() { std::string hex = "FFFF6472"; // 以16进制解析字符串,转换为long类型 long temp_val = std::strtol(hex.c_str(), nullptr, 16); int dec = static_cast<int>(temp_val); printf("%d", dec); // 输出-39822 return 0; }
注:若你的编译器中int为32位、long长度不小于32位时,该转换会正确识别补码对应的负数结果。
方法二:使用std::stoul先转无符号再转有符号
先将十六进制字符串转为无符号长整数,再强制转换为int,这种方式更稳妥,避免溢出异常:
#include <string> #include <cstdio> int main() { std::string hex = "FFFF6472"; // 解析为无符号十六进制值 unsigned long ul_val = std::stoul(hex, nullptr, 16); // 强制转换为int,利用补码规则得到负数 int dec = static_cast<int>(ul_val); printf("%d", dec); // 输出-39822 return 0; }
内容的提问来源于stack exchange,提问作者wsys
相关产品推荐
相关产品推荐

