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);
std::string has a larger interface.And of course, if you already have a string object
myString.insert(0, static_cast<const char*>(data), size);
^^ -- starting index
which calls
basic_string& insert( size_type index, const CharT* s, size_type count );
Inserts the first count characters from the character string pointed to by s at the position index. s can contain null characters.
std::string.std::stringis just a string, not a zero-terminated stringstd::string, or wouldstd::vector<char>be more suitable?std::vector<char>overstd::string(aside of readability)?\0tagged on at the end. So it really depends on your use-case.