4

I have an array of double:

QVector<double> Y(count);

I need to pack it to QByteArray to send via Ethernet.

So I did it. It was not too hard:

QByteArray line;
line.clear();
line.append(QByteArray::fromRawData(reinterpret_cast<const char*>(Y.data()),
count*sizeof(double)));

I try use this code to unpack the data from QByteArray recv :

QVector<double> data((line.size())/sizeof(double));
QByteArray dou(sizeof(double),0x0);
for(int i = 0; i<data.count(); i++){
    dou = recv.mid(i*sizeof(double),sizeof(double));
    data[i] = *reinterpret_cast<const double*>(dou.data());
    dou.clear();
}

But I don’t like it. I want to find out elegant way to unpack from QByteArray to QVector<double> Can you help me?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Dlash
  • 154
  • 3
  • 11

2 Answers2

8

you can use a QDataStream which will encode the data in binary in a specific format. (more specifically first the number of items (int32) and then each item)

QVector has overloads for the stream operators

QByteArray line;
QDataStream stream(&line, QIODevice::WriteOnly);
stream << y;

and to read:

QVector<double> data;
QDataStream stream(line);
stream >> data;
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
0

The common practice is to serialize the data as a text. This will make your server and client portable. Sending a binary data over the network is not a good idea. You can create your own text protocol, or use the existing one (like Google Protocol Buffers).

DmitryARN
  • 648
  • 3
  • 10
  • 2
    I'm not down voting you, but disagree with your answer. Protocol Buffers is a binary protocol. TCP and UDP are also. – wood_brian Mar 18 '14 at 22:26
  • I agree that G.P.B. is a binary protocol. I meant that one need to use a strictly defined protocol like QDataStream or G.P.B to send data and avoid sending a pure C binary data with the help of reinterpret_cast. – DmitryARN Mar 19 '14 at 12:14