I would like to convert an array into a QByteArray in Qt. Can someone explain the concept? Please provide an example.
问题:
回答1:
QByteArray
has a constructor that does just this.
This is how to use it:
const char* data; int size; // these variables should be correctly set to your array and size
QByteArray ba(data, size);
I used a pointer for the data, but arrays decay to pointers when passed as parameters so it's the same. This constructor will make a deep copy of the data. That means it will only take ownership of the copy it makes, and the data you used might need to be deallocated if it was allocated dynamically.
For arrays of other types than char
you are essentially doing serialization:
int data[30];
for (int i = 0; i < 30; ++i)
{
ba.append((const char*)(data + i), sizeof(int));
}
The above code will insert the bytes that make up your ints into a QByteArray
. Be careful though, since at this point indexing the QByteArray
won't return the ints but the bytes they are made of.
To convert a QString (which is not what you asked but added a comment asking it) use one of the appropriate member functions of QString
:
QByteArray ba = str.toLocal8bit();
QByteArray ba2 = str.toLatin1();
QByteArray ba3 = str.toUtf8();
QByteArray ba4 = str.toAscii();
To decide which one to use, you must know the encoding of your string. To convert between encodings, use QTextCodec
回答2:
An array of what? Assuming you mean a null terminated char array:
#include <QtCore>
int main(int argc, char *argv[])
{
const char* myArray = "Hello World!";
QByteArray myByteArray = QByteArray(myArray);
}
回答3:
To store an array in QByteArray i've adapted method described here: http://smartqt.blogspot.ru/2014/05/how-to-convert-struct-in-and-from.html
My version for int array is
QByteArray serialize(int* ar, int ar_size)
{
QByteArray result;
QDataStream stream (&result, QIODevice::WriteOnly);
stream<<ar_size;
for (int i=0; i<ar_size; i++)
stream<<ar[i];
return result;
}
void deserialize(const QByteArray& byteArray)
{
QDataStream stream(byteArray);
int ar_size=0;
stream>>ar_size;
int* ar = new int[ar_size];
for (int i=0; i<ar_size;i++)
stream>>ar[i];
}
Cheers!