C++ implementation of string access to binary data methods

  • 2020-04-02 02:49:29
  • OfStack

This article illustrates the C++ implementation of string access to binary data method, to share for your reference. Specific methods are analyzed as follows:

In general, STL strings are powerful and comfortable to use, and this time in the code involves accessing binary data with strings, which is documented here for future reference.

The first mention of STL string in resources: http://www.cplusplus.com/reference/string/string/, do not understand friend may have a look.

In data transmission, the buffer of binary data is generally stored in the large array preset by the system, instead of STL string, etc., such as:


const int max_length = 1024 * 1024;
unsigned char data[max_length];

Because binary data might contain 0x00 (that is, '\0'), which happens to be the end of the string flag...

If our code is written as follows:


char data[max_length];
size_t length = sockClient.read_some(boost::asio::buffer(data), ec);
string strData(data);

All I can say is, this should work fine with the string, because if it's binary, it will be truncated by the string's constructor, causing strData to be inconsistent with data.

In fact, a simple demo can illustrate the problem, such as the following code:


#include <string>
#include <iostream>
using namespace std;

int main()
{
    char data[] = {'A','b',0x00,'c','d'};
    string str1(data),str2(data,sizeof(data));
    cout<<str1<<endl;
    cout<<str1.size()<<endl;
    cout<<str2<<endl;
    cout<<str2.size()<<endl;
    return 0;
}

The operation effect is as follows:


Ab

2

Abcd

5 

It's not hard to see from the results that the str2 approach ensures that the data in the string is the same as the data in the original data. This is because different constructors are used, resulting in completely different structures, which can be understood by looking at the specific constructor instructions in the url I gave earlier. To return to the previous question, if we want to save the binary, we should do the following:


char data[max_length];
size_t length = sockClient.read_some(boost::asio::buffer(data), ec);
string strData(data,length);

If you want to fetch data, it is also simple (this also takes socket data for example) :


......
// deal with strData
......
boost::asio::write(sockClient, boost::asio::buffer(strData.c_str(),strData.length()));

Here, strdata.c_str () is the data, and strdata.length () is the length of the data to be sent. (you can also use strdata.size ().)

Of course, we here use string to access binary data, also just for the convenience of operation, feel this is not too good, there should be a lot of friends do not advocate this practice, here to provide an idea, we feel good to adopt, feel bad to laugh it off, ha ha...

Hope that the article described in the C++ programming to help you.


Related articles: