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

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

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

But I want to solve this problem correctly using memcpy function.

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

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

Please help me find the most elegant solution to this problem.

+5
source share
3 answers

Since we are just building a string, there is a constructor std::string 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 do not create a string and instead assign an existing one, you still prefer to use assign() . This function is intended 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 line really has enough data to copy. And then just copy it using &str[0] as the destination address & dagger; :

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

& dagger; Pre-C ++ 11 there is technically no guarantee that strings are stored in memory contiguously, although in practice this has been done anyway.

+11
source

You need to set the row size so that the buffers with the proper size in order to receive the data, and to expel the constant from the pointer that you get from data()

 std::string newString; newString.resize(length); memcpy((char*)newString.data(), &bytes[startIndex], length); 

Of course, all this is in the area of ​​undefined behavior, but pretty standard nonetheless.

-1
source

This is a hack and, as you said, wrong, but it is possible, since the STL guarantees that std::string has continuous storage:

 std::string str(32, '\0'); std::strcpy(const_cast<char*>(str.data()), "REALLY DUDE, IT ILLEGAL WAY"); 

Of course, you can use std::memcpy in the same way (I used strcpy only to copy a line with zero completion) ...

In your case:

 str.resize(length); memcpy(const_cast<char*>(str.data()), bytes + startIndex, length); 
-3
source

Source: https://habr.com/ru/post/1232295/


All Articles