Appending quint16 to QByteArray



  • Hi,

    I would like to append a quint16 variable to a QByteArray to write to a file.
    A quint16 is made of 2 bytes, right ?
    So I wrote:

    QByteArray qbatow;
    ...
    quint16 towrite = 256;
    qbatow = qbatow.append(towrite);
    

    The trouble is in the file: I always get 1 byte only in the file instead 2 bytes. I get the LSB, that's to say 00.

    Any idea ?

    Thanks


  • Qt Champions 2016

    @mulfycrowh

    QByteArray qbatow;
    
    QDataStream out(&qbatow, QIODevice::WriteOnly | QIODevice::Append);
    out.setByteOrder(QDataStream::BigEndian);
    
    quint16 towrite = 256;
    out << towrite;
    


  • No ! I don't want to use the operator <<. I use writeRawData



  • I found the solution :

    	quint16 towrite = 256;
    	char* charToWrite = (char*)&towrite;
    	qbatow = qbatow.append(charToWrite, sizeof(quint16));
    
    	out.writeRawData(qbatow.data(), qbatow.length());
    

    It's OK in the file : 00 01



  • It is better to use '<<' operator with QDataStream. Just configure QDataStream with desired BigEndian/LowEndian.



  • No it is not better. First of all, I used << and I didn't get the right count of bytes because depending of serialization. It's better to use writeRawData for my purpose.


  • Qt Champions 2016

    @mulfycrowh

    No it is not better.

    Yes, it is, you just don't realize it yet. Run your program on Intel and on PowerPC and compare the data you get in the byte array.

    First of all, I used << and I didn't get the right count of bytes because depending of serialization.

    Then you did something wrong.

    It's better to use writeRawData for my purpose.

    I don't know what exactly is your purpose, but I really, really doubt writeRawData is better.


Log in to reply
 

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