C++中将十六进制字符串转为十进制整数有两种常用方法:1. 使用std::stoul函数,支持指定进制(如16),可处理带或不带"0x"前缀的字符串,语法简洁且错误处理明确;2. 使用std::stringstream,需配合std::hex操纵符,但不自动识别"0x"前缀,需手动去除。推荐优先使用stoul,代码更现代简洁。

在C++中,将十六进制字符串转换为十进制整数是常见的需求,比如解析颜色值、内存地址或协议数据。有两种常用且可靠的方法:使用标准库函数 stoul 和使用 stringstream。下面分别介绍它们的用法和注意事项。
std::stoul(string to unsigned long)是C++11引入的字符串转无符号长整型函数,支持指定进制,非常适合处理十六进制字符串。
基本语法:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
int main() {
std::string hex = "1A";
unsigned long decimal = std::stoul(hex, nullptr, 16);
std::cout << "Hex " << hex << " -> Decimal " << decimal << std::endl;
// 输出:Hex 1A -> Decimal 26
return 0;
}
注意:如果字符串包含 "0x" 前缀,std::stoul 同样能正确识别。但如果 base 明确设为 16,则前缀不是必须的。
stringstream 是传统但灵活的方式,通过流操作实现类型转换。使用 std::hex 操纵符告诉流按十六进制读取数据。
步骤如下:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string hex = "1A";
std::stringstream ss;
unsigned int decimal;
ss << std::hex << hex;
ss >> decimal;
std::cout << "Hex " << hex << " -> Decimal " << decimal << std::endl;
// 输出:Hex 1A -> Decimal 26
return 0;
}
注意:stringstream 不自动识别 "0x" 前缀,若字符串带 "0x",需先去掉,否则转换可能失败或结果为 0。
stoul 更简洁,适合现代C++项目,直接支持进制参数,错误处理也更清晰(如抛出异常应对非法字符)。而 stringstream 更灵活,适用于复杂格式解析,但在单纯进制转换场景稍显繁琐。
建议优先使用 stoul,尤其在只需一次简单转换时。若已在使用流处理其他逻辑,也可统一用 stringstream 保持一致性。
基本上就这些,选择哪种方式取决于你的编码风格和项目需求。
以上就是C++如何将十六进制转为十进制_C++ stoul与stringstream转换方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号