Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put bytes from unsigned char array to std::string using memcpy() function

I have std::string variable. And I need to put some bytes from array of unsigned chars to it. I know the first byte and the the legth.

I can use the std::string::assign function. I've done it.

But I want to solve that issue in a right way using the memcpy function.

std::string newString;
memcpy(&newString, &bytes[startIndex], length);

I know it is wrong. I have researched and found some ideas using std::vector.

Please help me to find the most elegant solution for this issue.

like image 878
Alex Balabanov Avatar asked Sep 25 '15 17:09

Alex Balabanov


1 Answers

Since we're just constructing the string, there is a std::string constructor that takes two iterators:

template< class InputIt >
basic_string( InputIt first, InputIt last, 
              const Allocator& alloc = Allocator() );

which we can provide:

std::string newString(&bytes[startIndex], &bytes[startIndex] + length);

If we're not constructing the string and are instead assigning to an existing one, you should still prefer to use assign(). That is precisely what that function is for:

oldString.assign(&bytes[startIndex], &bytes[startIndex] + length);

But if you really insist on memcpy() for some reason, then you need to make sure that the string actually has sufficient data to be copied into. And then just copy into it using &str[0] as the destination address:

oldString.resize(length); // make sure we have enough space!
memcpy(&oldString[0], &bytes[startIndex], length);

Pre-C++11 there is technically no guarantee that strings are stored in memory contiguously, though in practice this was done anyway.

like image 111
Barry Avatar answered Oct 13 '22 23:10

Barry