Given
const void * data = ...;
size_t size = ...;
std::string message(???)
How to construct std::string
from raw pointer to data and size of the data? data
may contain NUL characters.
string constructor can work with char*
, that contains \0
, if size
is right.
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 does not point at an array of at least count elements of CharT.
So just use
std::string message(static_cast<const char*>(data), size);
You can cast data
to const char*
, then use the std::string
two iterator constructor.
const char* sdata = static_cast<const char*>(data);
std::string message(sdata, sdata + size);
Note that is all you need is a byte buffer, it might be simpler and clearer to use an std::vector<unsigned char>
instead.
const unsigned char* sdata = static_cast<const unsigned char*>(data);
std::vector<unsigned char> message(sdata, sdata + size);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With