Search code examples
qttype-conversionqt5unpackqbytearray

How to unpack 32bit integer packed in a QByteArray?


I'm working with serial communication, and I receive 32bit integers in a QByteArray, packed in 4 separate bytes (little-endian). I attempt to unpack the value from the 4 bytes using QByteArray::toLong() but it fails the conversion and returns the wrong number:

quint8 packed_bytes[] { 0x12, 0x34, 0x56, 0x78 };
QByteArray packed_array { QByteArray(reinterpret_cast<char*>(packed_bytes),
                                     sizeof(packed_bytes)) };
bool isConversionOK;
qint64 unpacked_value { packed_array.toLong(&isConversionOK) };
// At this point:
// unpacked_value == 0
// isConversionOK == false

The expected unpacked_value is 0x78563412 (little-endian unpacking). Why is the conversion failing?


Solution

  • You can use a QDataStream to read binary data.

    quint8 packed_bytes[] { 0x12, 0x34, 0x56, 0x78 };
    QByteArray packed_array { QByteArray(reinterpret_cast<char*>(packed_bytes), sizeof(packed_bytes)) };
    QDataStream stream(packed_array);
    stream.setByteOrder(QDataStream::LittleEndian);
    int result;
    stream >> result;
    qDebug() << QString::number(result,16);