6

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;
3
  • 3
    How do you want your uint8_t to be converted: as numbers or as characters? E.g., should 65 become "65" or "A"? Commented Mar 28, 2015 at 17:49
  • I think this link will help you stackoverflow.com/questions/29298204/… Commented Mar 28, 2015 at 18:07
  • key seems to be your data source and data destination. Could you fix your code? Commented Mar 28, 2015 at 18:09

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Without the cast, the string is still empty. With the cast, it works. If the key array contains 0x1F, 0x1F, 0x1F, 0x1F, and 0x1F, then I would want the string to be 1F1F1F1F1F.
In order to print values as uppercase hex, you can use std::uppercase and std::hex manipulators. I edited my answer to add this info.
Case isn't too important. But the std::hex and int casting was perfect. Thanks so much!
3

Probably the easiest way is

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

or C-style:

std::string str = (char *) arr;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.