Convert array of uint8_t to string in C++
Asked Answered
N

2

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;
Nason answered 28/3, 2015 at 17:41 Comment(3)
How do you want your uint8_t to be converted: as numbers or as characters? E.g., should 65 become "65" or "A"?Tourney
I think this link will help you #29298704Piggott
key seems to be your data source and data destination. Could you fix your code?Theocrasy
E
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.

Exhale answered 28/3, 2015 at 17:48 Comment(3)
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.Nason
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.Exhale
Case isn't too important. But the std::hex and int casting was perfect. Thanks so much!Nason
C
3

Probably the easiest way is

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

or C-style:

std::string str = (char *) arr;
Cromlech answered 11/2, 2021 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.