Reputation: 244
I want to convert an array of integers into hex form, then concatenate all off the hex values into one C++ string. The integers were originally uint8_t
, but I read about how to convert them to int
with no problem. 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:
41a9ffb9588717989367b3ec942233d5d9a982f8658c1073a87262da43fd42c9
How can I store this value as a string? I tried creating a 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. If you're wondering, the error is
error: invalid operands to binary expression ('__iom_t4<char>' and 'std::__1::__iom_t6')
Upvotes: 1
Views: 877
Reputation: 726479
Replacing cout
with std::stringstream
will do the job:
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();
Upvotes: 6