trouble with QByteArray

  • i done this operation
    quint32 registry =0x00000000;
    quint8 value1l=3;
    quint8 value2=0;
    quint16 value3=8191;
    quint16 value4=29;

    QByteArray b;

    i get in debugger this one

    b "15728579" QByteArray
    [0] 49 '1' char
    [1] 53 '5' char
    [2] 55 '7' char
    [3] 50 '2' char
    [4] 56 '8' char
    [5] 53 '5' char
    [6] 55 '7' char
    [7] 57 '9' char

    why we get 8 Byte?
    i think it schoud be 6 Byte because
    value 1 ist 1Byte
    value 2 ist 1Byte
    value 3 ist 2 Byte
    value 4 ist 2Byte
    where may i think false ?

  • Qt Champions 2016


    why we get 8 Byte?

    Sets the byte array to the printed value of n in base base (10 by default) and returns a reference to the byte array. The base can be any value between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

    Your number has 8 digits, so the string (stored in the byte array) contains 8 characters.

    i think it schoud be 6 Byte because

    If I understand correctly what you're trying to do, the byte array should be 4 bytes long, because qint32 registry is 32 bits (or 4 bytes) in size.

    where may i think false ?

    As I suggested in your previous thread, you should mask your numbers, because if the value1 variable has a value larger than 15, then this line:


    could simply produce incorrect values.

    That aside you can create byte array by casting the data appropriately:

    QByteArray data = QByteArray::fromRawData(reinterpret_cast<char * >(&registry), sizeof(registry));

    However you should be aware this doesn't take into account the endianness of the integer. If you need a portable way to transmit that data (for example through a network) you can serialize it with a data stream:

    QByteArray data;
    QDataStream stream(&data);
    stream << registry;

    So depending on what byte-order the binary data is expected to be in, you can call QDataStream::setByteOrder if applicable.

    What you're trying to do with shifting can also be done with a union a struct and some bit fields as well:

    union  {
        struct   {
            qint8 field1 : 4;
            qint8 field2 : 2;
            qint16 field3 : 13;
            qint16 field4 : 13;
        } flags;
        char * raw;
    } dataVar;
    // Fill the data
    dataVar.flags.field1 = value1;
    dataVar.flags.field2 = value2;
    dataVar.flags.field3 = value3;
    dataVar.flags.field4 = value4;
    // Convert to byte array
    QByteArray data = QByteArray::fromRawData(dataVar.raw, sizeof(dataVar.flags));

    Which is used a bit more intuitively.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.