1

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?

Marco A.
  • 43,032
  • 26
  • 132
  • 246

4 Answers4

12

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;
leemes
  • 44,967
  • 21
  • 135
  • 183
1

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.

HappyCactus
  • 1,935
  • 16
  • 24
0

Today this conversion is even simpler:

QVector<double> vec;
// populate vector
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << vec;
ajeh
  • 2,652
  • 2
  • 34
  • 65
  • Will "<<" flush all the elements in "vec" to the stream? – diverger Mar 17 '18 at 04:45
  • I do not use Qt for a couple years, so dunno, but a simple test should give you the answer. – ajeh Mar 22 '18 at 20:49
  • Someone has just downvoted a simplified syntax answer w/o providing any motivation for downvoting. Sounds like this is retaliatory downvoting or trolling and therefore has no place on SO. This resource is becoming a cesspool day by day. – ajeh Sep 04 '18 at 19:24
0

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.

bobbaluba
  • 3,584
  • 2
  • 31
  • 45