'convert uint8_t array to string in c++

This can be marked solved. The problem was the print macro. ESP_LOGx can't put out c++ Strings.

I'm trying to convert an uin8_t array to a string in c++. The array is defined in a header file like this:

uint8_t mypayload[1112];

Printing the array itself works, so I'm sure it's not empty.

now I'm trying to convert it to a string:

string qrData; 
std::string qrData(reinterpret_cast<char const*>(mypayload), sizeof mypayload);

I also tried: qrData = (char*)mypayload;

printing the string results in 5 random chars.

Does anybody have hint where I made a mistake?



Solution 1:[1]

The only correct comment so far is from Some programmer dude. So all credits go to him.

The comment from Ian4264 is flat wrong. Of course you can do a reinterpret_cast.

Please read here about the constructors of a std::string. You are using constructor number 4. The description is:

4) Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if [s, s + count) is not a valid range.

So, even if the string contains 0 characters, the C-Style string-"terminator", all bytes of the uint8_t arrays will be copied. And if you print the string, then it will print ALL characters, even the none printable characters after the '\0'.

That maybe your "random" characters. Because the string after your "terminator" does most probably contain uninitialized values.

You should consider to use the constructor number 5

5) Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range.

And if you need to add bytes, also possible. The std::string can grow dynamically.

BTW: you do define your "std::string qrData" double, which will not compile

Solution 2:[2]

Since you know the size of your data in another variable, why are you using sizeof? It will give you the size of the array, not the size of your data.

This should give you the right result, assuming no other errors in your code

std::string qrData(reinterpret_cast<char const*>(mypayload), data->payload_len);

Incidentally in the code you quoted why is qrData declared twice? That seems a bit suspicious.

Solution 3:[3]

qrData = (const char*)mypayload;

string is accept only const char*.

Solution 4:[4]

String s = String((char *)data, len); //esp32

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armin Montigny
Solution 2 john
Solution 3 Tarmo
Solution 4 a442509097