user7679831
user7679831

Reputation:

Qt data type serialization

could someone please provide an example of how one might serialize something like a QColor variable, and then store the bits in a QString/QBitArray/Vector (whatever is optimal). I was hoping to use QDataStream, but the only examples I can find include writing the data to a file.

Upvotes: 0

Views: 818

Answers (1)

Vladimir Bershov
Vladimir Bershov

Reputation: 2832

QColor can be serialized to QDataStream directly, without any conversions. QDataStream itself, in turn, can write the data to any QIODevice sublass or to a QByteArray.
See Serializing Qt Data Types.

Example:

Serialize color to QByteArray:

QColor color(Qt::red);

QByteArray ba;
QDataStream out(&ba, QIODevice::WriteOnly);
out << color; // serialized to ba

qDebug() << ba.size();

Serialize to TCP socket:

auto socket = new QTcpSocket;
socket->connectToHost(addr, port);
if(socket->waitForConnected())
{
    QDataStream out(socket);
    out << color; // written to socket
}

Qt has universal serialization rules for major core data types. You can serialize QColor directly to a io-device you need, or to QByteArray.


You can also present color as a string. But it is not a serialization.

QString colorName = color.name(); // the name of the color in the format "#RRGGBB"; i.e. a "#" character followed by three two-digit hexadecimal numbers
qDebug() << colorName;

About changing concrete bits in a QByteArray. See how to convert QByteArray to QBitArray and vice versa: https://wiki.qt.io/Working_with_Raw_Data

Converting Bits to Bytes (and back again)

QByteArray bytes = ...;

// Create a bit array of the appropriate size
QBitArray bits(bytes.count()*8);

// Convert from QByteArray to QBitArray
for(int i=0; i<bytes.count(); ++i) {
    for(int b=0; b<8;b++) {
        bits.setBit( i*8+b, bytes.at(i)&(1<<(7-b)) );
    }
}

...

QBitArray bits = ...;

// Resulting byte array
QByteArray bytes;

// Convert from QBitArray to QByteArray
for(int b=0; b<bits.count();++b) {
    bytes[b/8] = (bytes.at(b/8) | ((bits[b]?1:0)<<(7-(b%8))));
}

Do not forget about Byte Order: https://doc.qt.io/qt-5/qdatastream.html#setByteOrder

Upvotes: 1

Related Questions