c++ - 在字符串中存储多个十六进制值 C++

标签 c++

我想将一个整数数组转换为十六进制形式,然后将所有十六进制值连接成一个 C++ 字符串。整数最初是 uint8_t , 但我读到了如何将它们转换为 int没问题。到目前为止,我有这个。

for (int i = 0; i < HASHLEN; ++i) {
  int a = static_cast< int >(hash2[i]); // convert the uint8_t to a int
  cout << setfill('0') << setw(2) << hex << a; // print the hex value with the leading zero (important)
}

此代码在一行中打印数组中每个 int 的十六进制值,如下所示:

41a9ffb9588717989367b3ec942233d5d9a982f8658c1073a87262da43fd42c9

如何将此值存储为字符串?我尝试创建一个 string hash = "";在循环之前并使用这一行:

hash = hash + to_string(setfill('0') + setw(2) + hex + a);

而不是 cout行,但这不起作用。如果您想知道,错误是

error: invalid operands to binary expression ('__iom_t4<char>' and 'std::__1::__iom_t6')

最佳答案

std::stringstream 替换 cout将完成这项工作:

std::stringstream hexstr;
for (int i = 0; i < HASHLEN; ++i) {
    int a = static_cast< int >(hash2[i]);
    hexstr << setfill('0') << setw(2) << hex << a;
}
std::string res = hexstr.str();

关于c++ - 在字符串中存储多个十六进制值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252224/

相关文章:

c++ - 是否有迭代 POSIX 环境变量的函数?

c++ - boost::multi_index_container:从任意索引取equal_range,只执行一次循环

c++ - 可以动态填充 Visual Studio 项目中的 C++ 文件列表吗?

c++ - 在类构造函数中调用命名 lambda 与调用实际私有(private)函数的优点

C++:在同一架构层访问成员函数的建议

c++ - QT 如何创建自定义插槽?

c++ - 10 位数字但不是 18 位数字的整数溢出?

c++ - 如何在 Visual Studio 2017 中使用 GLOP 线性求解器 [C++]

c++ - 如何将 FBO 的文本附件绘制到默认帧缓冲区?

抽象类的C++工厂方法模式