使用std::stoi并指定基数16可将十六进制字符串转为整数,支持带或不带"0x"前缀的字符串,需处理invalid_argument和out_of_range异常以增强健壮性;超范围值应使用stoul或stoull。

在C++中,将十六进制字符串转换为整数(int)是一个常见需求,尤其是在处理颜色值、内存地址或底层数据解析时。利用标准库中的 std::stoi 函数配合正确的参数设置,可以轻松实现这一转换。
使用 stoi 直接转换十六进制字符串
std::stoi 支持自动识别以 "0x" 或 "0X" 开头的十六进制字符串,也可以通过指定基数(base)来强制按16进制解析。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string hex_str1 = "0xFF"; // 带 0x 前缀
std::string hex_str2 = "FF"; // 不带前缀
int val1 = std::stoi(hex_str1, nullptr, 16); // 自动识别或显式指定 base=16
int val2 = std::stoi(hex_str2, nullptr, 16); // 必须指定 base=16
std::cout <p>关键点是第三个参数传入 <strong>16</strong>,表示按十六进制解析字符串。即使字符串没有 "0x" 前缀,也能正确转换。</p>
<h3>处理转换异常与非法字符</h3>
<p>如果输入字符串包含非十六进制字符(如 'G'、'Z' 或空格),<strong>std::stoi</strong> 会抛出 <strong>std::invalid_argument</strong> 异常。建议用 try-catch 包裹以增强健壮性。</p>
<font>安全转换示例:</font><p>
</p>
<pre class="brush:php;toolbar:false;">
#include <iostream>
#include <string>
#include <stdexcept>
int hex_to_int(const std::string& hex_str) {
try {
return std::stoi(hex_str, nullptr, 16);
} catch (const std::invalid_argument& e) {
std::cerr <p>这样可以在实际项目中避免程序因脏数据崩溃。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill12795" title="deepstream-dev"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="deepstream-dev" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill12795" title="deepstream-dev" class="overflowclass">deepstream-dev</a>
<p class="overflowclass">使用 Python pyservicemaker API 进行 NVIDIA DeepStream SDK 开发。在构建视频分析流水线、基于 GStreamer</p>
</div>
<a rel="nofollow" href="/xiazai/skill12795" title="deepstream-dev" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<h3>支持大数值:使用 stol 或 stoul</h3>
<p>如果十六进制字符串表示的值可能超过 int 范围(如 "0xFFFFFFFF"),应改用 <strong>std::stoul</strong>(返回 unsigned long)或 <strong>std::stoll</strong> / <strong>std::stoull</strong> 处理更大范围。</p>
<font>例如:</font><p>
</p>
<pre class="brush:php;toolbar:false;">
unsigned long val = std::stoul("FFFFFFFF", nullptr, 16); // 返回 4294967295
这对于解析32位以上地址或哈希值非常有用。
基本上就这些。掌握 std::stoi 的 base 参数和异常处理机制,就能灵活应对各种十六进制字符串转整数的场景。不复杂但容易忽略细节。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










