简体   繁体   中英

How to convert QVector<double> to QBytearray

I would like to convert QVector<double> to QBytearray , and I have no idea on how to do this. I tried this but the program crashes:

QVector<double> vec;
QByteArray arr = QByteArray::fromRawData(reinterpret_cast<const char*>(vec),vec.size());
for(int i = 0; i< vec.size(); i++)
    arr.append(reinterpret_cast<const char*>(vec.data(&numberOfData),sizeof(double));

Can someone tell me how to do it properly?

You can use QVector::constData to get a pointer to the (const) raw data contained in the vector. However, you also need to multiply the size by the size of a single entry, ie sizeof(double) . You don't need a loop afterwards like in your code.

QByteArray data = QByteArray::fromRawData(
        reinterpret_cast<const char*>(vec.constData()),
        sizeof(double) * vec.size()
    );

You could also use QDataStream to do the conversion, resulting in a much cleaner code, which also takes care of potential byte ordering issues .

QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
for (auto x : vec)
    stream << x;

You must pass through a native array, so your QByteArray will receive a sequence of contiguous bytes.

double *bytes = new double[vec.size()];
for (int i = 0; i < vec.size(); ++i) {
   bytes[i] = vec[i];
}
QByteArray array = QByteArray::fromRawData(reinterpret_cast<void*>(bytes));
delete []bytes;

Disclaimer: untested code.

--- Update ---

As leemes correctly pointed out, you DON'T need to allocate and copy a byte array, QVector already provides two access functions to raw data. So you can simply use data() and constData(). Please see his response.

Today this conversion is even simpler:

QVector<double> vec;
// populate vector
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << vec;

I was a bit annoyed by this too. Building on other answers here, I came up with this:

template<typename data_type>
QByteArray toByteArray(data_type data) {
    QByteArray bytes;
    QDataStream stream(&bytes, QIODevice::WriteOnly);
    stream << data;
    return bytes;
}

This should let you write the following code:

QVector<double> vec{1, 2, 3, 4};
auto bytes = toByteArray(vec);

And will also work for other types that support streaming to a QDataStream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM