Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 835
Alex Parker Avatar asked Mar 28 '15 17:03

Alex Parker


2 Answers

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.

like image 183
Ove Avatar answered Sep 21 '22 07:09

Ove


Probably the easiest way is

uint8_t arr[];
// ...
std::string str = reinterpret_cast<char *>(arr); 

or C-style:

std::string str = (char *) arr;
like image 34
kraxor Avatar answered Sep 18 '22 07:09

kraxor