std::hex 仅设置输出格式,不执行类型转换;它只影响后续整数在 std::ostream 中的十六进制显示,不会将 int 自动转为 std::string。

std::hex 本身不转换,只是设置输出格式
std::hex 是一个 I/O 操纵器(manipulator),它只影响后续对 std::ostream(如 std::cout 或 std::stringstream)的整数输出行为,**不会自动把 int 变成 std::string**。直接写 std::hex 得到的是一个临时的格式化对象,不是字符串。
常见错误是以为这样就能拿到字符串:
std::string s = std::hex <p>正确路径必须经过 <code>std::stringstream</code> 中转,并调用 <code>.str()</code> 提取结果。</p> <h3>基础转换:用 string<a style="color:#f60; text-decoration:underline;" title="stream" href="https://m.php.cn/zt/19633.html" target="_blank">stream</a> + std::hex + std::uppercase</h3> <p>最常用、可读性好的方式是组合 <code>std::stringstream</code> 和格式控制:</p>
-
std::hex启用十六进制输出(小写字母 a–f) -
std::uppercase让字母变成大写(A–F) -
std::setw和std::setfill控制补零宽度(如固定 4 位)
示例(转为小写、无前缀、不补零):
int x = 255;
std::stringstream ss;
ss
<p>如果要大写、补零到 4 位:</p>
<pre class="brush:php;toolbar:false;">ss.str(""); ss.clear(); // 清空重用
ss
<p>注意:<code>std::setw</code> 只对**下一个输出项**生效,不能设一次管全程。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<h3>不带 stream 的替代方案:std::format(C++20)</h3>
<p>C++20 引入了 <code>std::format</code>,更接近 Python 的 <code>format()</code>,避免 stream 状态管理问题:</p>
<pre class="brush:php;toolbar:false;">std::string s = std::format("{:x}", 255); // "ff"
std::string S = std::format("{:X}", 255); // "FF"
std::string p = std::format("{:#x}", 255); // "0xff"
std::string w = std::format("{:04x}", 255); // "00ff"
优势:无状态、线程安全、语法直观;缺点:目前 MSVC / GCC / Clang 对 std::format 的完整支持仍需开启实验性选项(如 -std=c++20 -fformat-extensions),且部分标准库实现尚未完全落地。
容易踩的坑:符号扩展、负数、前缀与大小写混用
负数默认按补码输出,std::hex 不做符号处理:
int n = -1;
ss.str(""); ss.clear();
ss
<p>若想输出带符号的十六进制(如 "-ff"),需手动判断正负并处理绝对值:</p>
<pre class="brush:php;toolbar:false;">if (n
<p>其他典型陷阱:</p>
- 忘记清空
std::stringstream的状态位(如之前发生过failbit),导致后续写入失败 - 误用
std::showbase:它加的是0x前缀,但和std::uppercase组合后变成0X,不是所有场景都需要 - 用
std::ostringstream替代std::stringstream更语义清晰(只输出,不输入)
真正麻烦的从来不是“怎么转”,而是“转成什么样子”——要不要前缀、大小写、补零、符号处理、跨平台字长一致性(int 在不同平台可能是 32 或 64 位),这些细节得在第一次用时就想清楚,否则后期 patch 成堆。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










