Important: Please read the Qt Code of Conduct -

QByteArray qint32 and little endianness

  • Hello,

    I'm re-writing a small C program in QT. I have not used QT before and have very limited experience in C++. My program connects to a small device over serial and retrieves some values from it. I'm having a bit of a difficult time trying to build my binary packet, and wondered if there is a better or proper way doing it with QT and the included types. The packet consists of a byte or two bytes, and the format is in little endian. The data length is 4 bytes. But split into two 2Bytes. Below is an example of the packet.

    The packet consists of the following [Command - Byte] [Subcommand - Byte] [DataLength1 - 2Bytes] [Datalength2 - 2Bytes] [Data - nBytes]

    I'm using QByteArray for the packet and defined Command as an qint8, Subcommand as qint16, and Datalength as qint32. I then use QDataStream to assign the data as follows:

        QDataStream data(&_packet, QIODevice::WriteOnly);
        data << _command;
        data << _param1;
        data << _dataSize;

    This gives me the "correct" data with the correct final length and all that. The problem now is that I need to split dataSize into two Words, and assign them in little endian format. So the data ;

    CMD     PARAM   Length      DATA
    0x65    0x02    0xAABBCCDD  0X00

    Should be as below:

    CMD     PARAM   Len1    len2        DATA
    0x65    0x02    0xBBAA  0xDDCC      0X00

    The way I have been doing it in my small C program is using a typedef like below:

    typedef union _WORD_VAL {
    	WORD Word;BYTE Bytes[2];
    } WORD_VAL;
    WORD_VAL wParam;
    wParam = 10;
    byte[0] = wParam.Bytes[0];
    byte[1] = wParam.Bytes[1];

    So my question is; what is the best way to do this in QT or C++. Or is it easier to just define my own type like I did before.

    Any help would be greatly appreciated.

  • Hi, you can try setting the byte order directly in your QDataStream, like this:

    QDataStream data(&_packet, QIODevice::WriteOnly);
    data << _command;
    data << _param1;
    data << _dataSize;

  • Hi Hskoglund,

    Thank you very much for the reply and the solution. This is working perfectly!

    Much appreciated!

Log in to reply