c++ostringstreamuint8t

Convert array of uint8_t to string in C++


I have an array of type uint8_t. I want to create a string that concatenates each element of the array. Here is my attempt using an ostringstream, but the string seems to be empty afterward.

std::string key = "";
std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {                                               
  convert << key_arr[a]
  key.append(convert.str());
}

cout << key << endl;

Solution

  • 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.