我创建了一个向量std::vector<uint8_t> vec{ 0x0C, 0x14, 0x30 };
我想返回字符串“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;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,结果将为“122048”。哇,十六进制值存储在字节向量中,为什么我使用 to_string 得到十进制值而不是十六进制值?
我建议使用 astd::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;
}
Run Code Online (Sandbox Code Playgroud)
以相反的顺序进行:
+v将uint8_t/提升char为int,以便它输出值而不是 ASCII 字符。std::hex使其以十六进制格式输出 - 但 11 变成 B 而不是 0Bstd::setw(sizeof(v) * 2)将输出宽度设置为类型中字节数的两倍v- 这里只是 1*2。现在11变成“B”。std::setfill('0')将填充字符设置为0,最后将11变成0B。