C++ - Convert array of floats to std::string -


i have array of floats fixed length. want convert array binary string.

i cannot use const char * because string contain null-bytes. how use memcpy in case? have tried reinterpret_cast<string *>, won't work because string also/only storing pointers begin , end of data (correct me if wrong).

i'm constructing empty string:

string s; s.resize(arr_size); 

but how copy array of floats string?

basically, want dump memory region of fixed float array string.

don't hard me, i'm still learning c++

like this:

#include <algorithm> #include <string>  float data[10]; // populate  std::string s(sizeof data); char const * p = reinterpret_cast<char const *>(data);  std::copy(p, p + sizeof data, &s[0]); 

note sizeof data same 10 * sizeof(float), i.e. number of bytes in array.

update: suggested james, can better , write in 1 go:

char const * p = reinterpret_cast<char const *>(data); std::string s(p, p + sizeof data);  // beginning + length constructor 

or even:

#include <iterator>  std::string s(reinterpret_cast<char const *>(std::begin(data)),  // begin + end               reinterpret_cast<char const *>(std::end(data)));   // constructor 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -