How to build a C ++ string from a sequence of bytes?

Considering

const void * data = ...; size_t size = ...; std::string message(???) 

How to build std::string from raw pointer to data and data size? data may contain NUL characters.

+6
source share
4 answers

the string constructor can work with char* , which contains \0 if size right.

Creates a string with the first character count character of the string pointed to by s. s may contain null characters. The length of the string is counted. Undefined behavior if s does not point to an array of no less than countable CharT elements.

Therefore just use

 std::string message(static_cast<const char*>(data), size); 
+8
source

You can discard data in const char* and then use the std::string iterator constructor.

 const char* sdata = static_cast<const char*>(data); std::string message(sdata, sdata + size); 

Please note: all you need is a byte buffer, it can be simpler and more understandable to use std::vector<unsigned char> .

 const unsigned char* sdata = static_cast<const unsigned char*>(data); std::vector<unsigned char> message(sdata, sdata + size); 
+7
source

As long as the size indicates the correct number, the casting is excellent. You can have NULL somewhere std::string , and you don’t even need NULL to complete your buffer.

+1
source

And of course, if you already have a string object

 myString.insert(0, static_cast<const char*>(data), size); ^^ -- starting index 

which causes

 basic_string& insert( size_type index, const CharT* s, size_type count ); 

Β§

Inserts the first characters of the count from the character string pointed to by s in the position index. s may contain null characters.

+1
source

All Articles