简体   繁体   中英

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. 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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM