【问题标题】:Byte vector to hex stringstream DWORD aligned字节向量到十六进制字符串流 DWORD 对齐
【发布时间】:2026-02-16 08:45:01
【问题描述】:

我想将存储在std::vector<unsigned char> 中的字节转换为对齐的字符串流 DWORD(4 个字节)。

示例:

字节向量的内容:0x12 0x00 0x1B 0xAC 0x15 0xDF (6 Bytes)

std::stringstream stream;
//stream << std::hex << std::setfill('0') << std::setw(8) ???

流应该类似于:12001BAC 000015DF

std::copy 有没有简单的方法或如何实现?

【问题讨论】:

  • 请提供更多细节。 “???”是什么意思代表什么?
  • @JesseChisholm 这句话只是我的一个想法(已评论)!

标签: c++ vector hex stringstream


【解决方案1】:

是不是你不想要一个循环?

for(int i=0; i < bytevector.size(); ++i)
{
    if ((0 != i) && (0 == (i%4)))
        stream << " ";
    stream << std::hex << std::setfill('0') << std::setw(2) << byteVector[i];
}

【讨论】:

  • 我认为std::hexstd::setfill 可以脱离循环,它们会改变永久状态。