How to convert QVector<double> to QBytearray

时光毁灭记忆、已成空白 提交于 2019-12-08 14:01:26

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.

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, i.e. 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;

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!