数字向量到十六进制格式的字符串

Vector of number to string in hexadecimal format

我创建了一个向量std::vector<uint8_t> vec{ 0x0C, 0x14, 0x30 };

我想 return 字符串“0CD430”中向量的值。

我创建了这个简单的代码:

std::string vectorTostring(const std::vector<uint8_t>& vec)
{
    std::string result;
    for (const auto& v : vec)
    {
        result += std::to_string(v);
    }
    return result;
}

在这种情况下,结果将为“122048”。哇,十六进制值存储在字节向量中,为什么我使用 to_string?

得到十进制值而不是十六进制值

我建议使用 std::stringstream 和一些像这样的输出操纵器:

#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <iostream>

std::string vectorTostring(const std::vector<uint8_t>& vec)
{
    std::stringstream result;
    for (const auto& v : vec)
    {
        result 
            << std::setfill('0') << std::setw(sizeof(v) * 2)
            << std::hex << +v;
    }
    return result.str();
}

int main()
{
    std::cout << vectorTostring({ 0x0c, 0x14, 0x30 }) << std::endl;
}

倒序服用:

  • +vuint8_t/char 提升为 int,以便它输出值而不是 ASCII 字符。
  • std::hex 以十六进制格式输出 - 但 11 变成 B 而不是 0B
  • std::setw(sizeof(v) * 2) 将输出宽度设置为 v 类型字节数的两倍 - 这里只是 1*2。现在 11 变成了“B”。
  • std::setfill('0')设置填充符为0,最后11变成0B。