Parsing mixed binary data in C ++

I have a bunch of data that I process. It has mixed data types, some doubles, followed by some floats. This is how I began to parse doubles into a vector. I just want to get feedback if there is a better way to do this. I feel that there may be a way to do this more briefly.

BlobData::MyDoubles is a vector<double>;

    BlobData::MyDoubles MyClass::GetDataPointsFromBlob(const text* blob, const int numDoubles)
{
    BlobData::MyDoubles::value_type* doubles = new BlobData::MyDoubles::value_type[numDoubles];
    memcpy(doubles, blob, numDoubles*sizeof(BlobData::MyDoubles::value_type));
    BlobData::MyDoubles returnVal =  BlobData::MyDoubles(doubles,doubles+numDoubles);
    delete [] doubles;
    return returnVal;
}
+4
source share
1 answer

You do not need additional selection, since the vector will copy the content no matter what. To convert data from a pointer to void / char / whatever_blob, use reinterpret_castwhat it was created for. And you can build a vector with a pair of iterators (pointers are iterators).

vector<double> GetDataPoints(const char* blob, const int numDoubles) {
    const double* dbegin = reinterpret_cast<const double*>(blob);
    return { dbegin, dbegin + numDoubles };
}

, sizeof(double) - ++

P.S. ( ), . size_t.

+3

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


All Articles