Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 769
vladon Avatar asked Sep 08 '15 13:09

vladon


2 Answers

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);
like image 186
ForEveR Avatar answered Oct 05 '22 12:10

ForEveR


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);
like image 38
juanchopanza Avatar answered Oct 05 '22 11:10

juanchopanza