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

时间:2018-07-09 18:49:36

标签: 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')

1 个答案:

答案 0 :(得分:6)

cout替换为std::stringstream即可完成工作:

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();