Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to convert quint64 to 4 byte QByteArray



  • How can I convert a quint64 into a 4 byte QByteArray?

    I have a quint64 with the value of 19

    quint64 length = 19;
    

    Note: The length could also be much larger. I have to pass it to a QTcpSocket. The protocol requires that the first 4 bytes are the size of the whole message.

    The QByteArray should look like this:

    \x13\x00\x00\x00\
    

    How can I do that?



  • Use a QDataStream with a QBuffer:

       QBuffer buf;
       buf.open(QBuffer::ReadWrite);
       QDataStream stream(&buf);
    
       qint64 v=19;
       stream<<v;
       QByteArray arr=buf.buffer();
    

    The array looks like:
    "\x00\x00\x00\x00\x00\x00\x00\x13"
    By default QDataStream use big endian ( you can change to little endian)
    The array is 8 bytes length (qint64=8bytes)
    If you really want 4 bytes in length, you must use qint32 instead.



  • Use a QDataStream with a QBuffer:

       QBuffer buf;
       buf.open(QBuffer::ReadWrite);
       QDataStream stream(&buf);
    
       qint64 v=19;
       stream<<v;
       QByteArray arr=buf.buffer();
    

    The array looks like:
    "\x00\x00\x00\x00\x00\x00\x00\x13"
    By default QDataStream use big endian ( you can change to little endian)
    The array is 8 bytes length (qint64=8bytes)
    If you really want 4 bytes in length, you must use qint32 instead.



  • @mpergand Perfect. Thank you very much.


Log in to reply