[英]Store multiple hex values in a string c++
I want to convert an array of integers into hex form, then concatenate all off the hex values into one C++ string. 我想将整数数组转换为十六进制形式,然后将所有十六进制值连接成一个C ++字符串。 The integers were originally uint8_t
, but I read about how to convert them to int
with no problem. 整数最初是uint8_t
,但我读到了如何将它们毫无问题地转换为int
。 So far, I have this. 到目前为止,我有这个。
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)
}
This code prints the hex value of every int in the array on one line, like this: 这段代码在一行上打印数组中每个int的十六进制值,如下所示:
41a9ffb9588717989367b3ec942233d5d9a982f8658c1073a87262da43fd42c9
How can I store this value as a string? 如何将该值存储为字符串? I tried creating a string hash = "";
我尝试创建一个string hash = "";
before the loop and using this line: 在循环之前使用此行:
hash = hash + to_string(setfill('0') + setw(2) + hex + a);
instead of the cout
line, but this does not work. 而不是cout
,但这是行不通的。 If you're wondering, the error is 如果您想知道,错误是
error: invalid operands to binary expression ('__iom_t4<char>' and 'std::__1::__iom_t6')
Replacing cout
with std::stringstream
will do the job: 用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.