如何转换QVector< double>到QBytearray [英] How to convert QVector<double> to QBytearray
问题描述
我想将QVector<double>
转换为QBytearray
,并且我不知道如何执行此操作.
我试过了,但是程序崩溃了:
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?
推荐答案
您必须传递一个本机数组,这样QByteArray才能接收到一系列连续的字节.
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.
-更新---
正如leemes正确指出的那样,您不需要分配和复制字节数组,QVector已经提供了两个对原始数据的访问功能.因此,您可以简单地使用data()和constData(). 请看他的回应.
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.
这篇关于如何转换QVector< double>到QBytearray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!