How to convert QVector<double> to QBytearray
-
0 down vote favorite
I will convert QVector to QBytearray, and I have not idea 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?
-
Hi,
why do you want to convert QVector to QByteArray? Maybe you can do it with QVector directly.
According to what you want to do, there are several possibilities:
@
QVector<double> vec;
QByteArray array;// with streams:
QDataStream stream(&array, QIODevice::WriteOnly);
stream << vec;//with strings:
for (int i = 0; i < vec.size(); i++) {
array = array.append(QString("%1").arg(vec[i]));
}// ...
@You can reinterpret the double as char of course, but be aware, that double is 8 times as big as a char (platform dependent!). So you have to do some fancy bit shifting.
-
Please tell us what do you store in those double values and what do you really want to do. If all you need is to translate the doubles into string representation of the numbers, here is a simple way to do it:
@
foreach (double d, vec) {
arr += QByteArray::number(d);
}
@But I suspect your use case is different. Are the double values encoding something?
-
Thank you for reply!
I need to reinterprete QVector<double> as QBytearray, because i will display(QPixmap or QImage) my QVector as a image.
Do you have any idea how should i do it?
My vector values are in the range 0-3000, If it matter...
I apologize for my shortcomings. Just learning to Qt from a few weeks...
-
Why do you want to do that with a QByteArray? :D
Allocate an QImage with appropriate dimensions and insert the values pixel by pixel. You have to iterate over the whole vector anyway, since the range is not 0-255.
@
QVector<double> vec;
QImage image(vec.size(), 1, QImage::Format_ARGB32);
double MAX = 3000;
for (int i = 0; i < vec.size(); ++i)
{
int val = vec[i] / MAX * 255;
image.setPixel(i, 0, QColor(val, val, val).rgb());
}
@Maybe you want to do arrange the pixel in a different way, but I guess you can manage that ;)
Note that you should use QImage for direct pixel access. You can convert QImage to QPixmap easily with
@
QPixmap::fromImage()
@