You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

cout将memcpy合并的整数显示为十六进制,如何转为十进制显示?

How to Display the Integer in Decimal Format Instead of Hexadecimal

Hi Tillman,

The issue here is super straightforward—you've set the output stream to hexadecimal mode with std::hex earlier in your code, and stream formatting flags stick around until you explicitly change them. That's why your integer result is printing in hex, even though the memcpy worked perfectly for calculations.

Why your float function works fine

Just a quick side note: Float output isn't affected by integer formatting flags like std::hex or std::dec, which is why that function behaves as expected—no formatting conflict there.

Fixes to get decimal output for your integer

You have two simple, reliable options to fix this:

Option 1: Explicitly switch back to decimal before printing result

Add std::dec right before you output result to reset the stream to decimal mode:

std::memcpy(&result, buffer.get(), sizeof(result));
// Switch to decimal format here
out << " ---> " << std::dec << result << '\n';

Option 2: Save and restore the original stream flags (safer for broader code)

If you're worried about disrupting formatting for code that runs after this function, you can save the original stream flags before switching to hex, then restore them later:

// Save the original stream flags at the start
auto originalFlags = out.flags();

out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;
for (size_t i = 0; i < bytesRead; ++i) {
    out << ' ' << (int)buffer.get()[i];
}
std::memcpy(&result, buffer.get(), sizeof(result));

// Restore the original flags to reset formatting
out.flags(originalFlags);
out << " ---> " << result << '\n';

Either fix will make your result print in decimal instead of hex. For context, the ff85 value you're seeing translates to -123 as a 16-bit signed integer (or 65413 as an unsigned 32-bit integer)—the decimal output will show this correct numeric value instead of the hex string.

内容的提问来源于stack exchange,提问作者Tillman Ott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:59:20