【问题标题】:How to convert vector of uint8_t into std::string in C++?如何在 C++ 中将 uint8_t 的向量转换为 std::string?
【发布时间】:2022-01-09 08:26:48
【问题描述】:

我正在尝试将字节正确转换为字符串。但是转换后的字符串看起来像垃圾。我有以下代码:

#include <iostream>
#include <sstream>
#include <vector>

 std::string HexString( std::vector<std::uint8_t> &bytes ) {
                std::stringstream ss;
                for ( std::int32_t i = 0; i < bytes.size(); i++ ) {
                    if(i != 0)
                        ss << ",";
                    ss << bytes[i];
                }
                return ss.str();
}

int main() {
    std::vector<uint8_t> uuid = {
                 0x41,0x7c, 0xea, 0x9a,0xaf
    };
    
    std::string uuidString = HexString(uuid);
    
    std::cout << "Should be equal" << std::endl;
    std::cout << uuidString << std::endl;
    std::cout << "0x41, 0x7c, 0xea, 0x9a, 0xaf" << std::endl;

    return 0;
}

输出:

Both should be equal:
A,|,�,�,�
0x41, 0x7c, 0xea, 0x9a, 0xaf

正确的输出应该是:

Both should be equal:
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

任何建议将不胜感激。

【问题讨论】:

  • 字符串不是字节,而是字符。您将获得具有这些十六进制值的字符的输出。为什么要一串二进制数据? vectorarray 是使用二进制数据时使用的常规容器。
  • 流“输出”运算符&lt;&lt; 将写入all 基于char 的类型(并且uint8_t 基于char)作为字符,而不是整数.
  • 正如@Someprogrammerdude 提到的,您得到了这些数字的相应字符。 0x41 对应“A”,0x7c 对应“|”等等。 ypu 打印的其他“奇怪字符”要么是不可打印字符,要么是扩展 ascii 表中的字符(参见值here)。

标签: c++ c++11 c++14


【解决方案1】:
  • 您的uint8_t 值被解释为字符。将它们转换为整数以进行流操作
  • 使用std::hex 进行流操作,将整数转换为十六进制表示
  • 添加“0x”,因为std::hex 不会为您执行此操作。
  • 在逗号后添加一个空格
std::string HexString(std::vector<std::uint8_t> &bytes)
{
    std::stringstream ss;
    for (std::size_t i = 0; i < bytes.size(); i++)
    {
        if (i != 0)
        {
            ss << ", ";
        }
        ss << "0x" << std::hex << static_cast<int>(bytes[i]);
    }
    return ss.str();
}

这样,我得到:

Should be equal
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

【讨论】:

  • "将它们转换为整数以进行流操作。" -- 公平地说,uint8_t一个整数类型(def),它的值应该被这样解释。
  • 它可能是unsigned char 的typedef。如果没有演员表,我会在输出中得到 0xA, 0x|, 0x�, 0x�, 0x� 而不是十六进制值。糟糕。
  • @DevSolar uint8_t 通常是unsigned char 的别名,所以它可能非常讨厌。这是添加std::byte 的原因之一。
  • 通常,十六进制字节以 2 位打印。这个答案将打印例如5 为 0x5。在 C++ 中解决这个问题真的很麻烦:ss &lt;&lt; "0x" &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; std::right &lt;&lt; std::hex &lt;&lt; static_cast&lt;int&gt;(bytes[i]);.
  • @nielsen:很公平。但是,如果它们的宽度都一样,std::right 真的有必要吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
相关资源
最近更新 更多