简体   繁体   English

从QByteArray转换为double数组

[英]Convert from QByteArray to array of double

I have an array of double : 我有一个double数组:

QVector<double> Y(count);

I need to pack it to QByteArray to send via Ethernet. 我需要将它打包到QByteArray以通过以太网发送。

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 : 我尝试使用此代码从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? 我想找出从QByteArray解压缩到QVector<double>优雅方式QVector<double>你能帮助我吗?

you can use a QDataStream which will encode the data in binary in a specific format. 您可以使用QDataStream ,它将以特定格式对二进制数据进行编码 (more specifically first the number of items (int32) and then each item) (更具体地说,首先是项目数(int32)然后是每个项目)

QVector has overloads for the stream operators QVector 为流运营商提供了重载

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

and to read: 并阅读:

QVector<double> data;
QDataStream stream(line);
stream >> data;

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). 您可以创建自己的文本协议,也可以使用现有协议(如Google协议缓冲区)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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