Convert array of uint8_t to string in C++
Try this:
std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {
convert << (int)key[a];
}
std::string key_string = convert.str();
std::cout << key_string << std::endl;
The ostringstream
class is like a string builder. You can append values to it, and when you're done you can call it's .str()
method to get a std::string
that contains everything you put into it.
You need to cast the uint8_t
values to int
before you add them to the ostringstream
because if you don't it will treat them as chars. On the other hand, if they do represent chars, you need to remove the (int)
cast to see the actual characters.
EDIT: If your array contains 0x1F 0x1F 0x1F and you want your string to be 1F1F1F, you can use std::uppercase
and std::hex
manipulators, like this:
std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {
convert << std::uppercase << std::hex << (int)key[a];
}
If you want to go back to decimal and lowercase, you need to use std::nouppercase
and std::dec
.