c++datagramqbytearray

How segment properly a QByteArray data frome the readDatagram() function?


I try to take values from a Socket I'll receive from another program. Normally, the socket is divided into segments of 4 bytes, except particular case of 20 bytes data.

I know the method for read the signal, using this thread : How to receive proper UDP packet in QT?

So here the example I take from this topic:

while (socket->hasPendingDatagrams())
{
     QByteArray datagram;
     datagram.resize(socket->pendingDatagramSize());
     socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
    qDebug() <<"Message From :: " << sender.toString();
    qDebug() <<"Port From :: "<< port;
    qDebug() <<"Message :: " << datagram;
}

How and what to segment after that ?

Is that "datagram.data()" ? Just "datagram" ? Using substr like "QByteArray firstdata = (datagram.data()).substr(0,4)" don't work...

Is there another function ?

By example, for a datagram like (in Hex) : 00 00 00 02 00 00 00 01 00 00 (...) 43 46 , I want to split it like :

uint32_t a = (00 00 00 02);
uint32_t b = (00 00 00 01) ;
char c = (00 00 00 (...) 46);

Thank you !


Solution

  • If you want to slice QByteArray into pieces you can use QByteArray::mid (or QByteArray::sliced):

    QByteArray part1 = datagram.mid(0, 4);
    QByteArray part2 = datagram.mid(4, 4);
    QByteArray rest = datagram.mid(8);
    

    If you want to parse it too, you can use QDataStream:

    QDataStream ds{datagram};
    ds.setByteOrder(QDataStream::ByteOrder::BigEndian); // it is the default but let's be explicit
    
    uint32_t a, b;
    char rest[8];
    
    ds >> a >> b;
    ds.readRawData(rest, 8);