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 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.
来源:https://stackoverflow.com/questions/26841755/how-to-convert-qvectordouble-to-qbytearray