Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to convert quint64 to 4 byte QByteArray
Forum Updated to NodeBB v4.3 + New Features

How to convert quint64 to 4 byte QByteArray

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 1.6k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Infinity
    wrote on last edited by Infinity
    #1

    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?

    1 Reply Last reply
    0
    • M Offline
      M Offline
      mpergand
      wrote on last edited by
      #2

      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.

      I 1 Reply Last reply
      1
      • M mpergand

        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.

        I Offline
        I Offline
        Infinity
        wrote on last edited by
        #3

        @mpergand Perfect. Thank you very much.

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved