0

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 !

Batfly
  • 13
  • 6
  • I just edit it to update my problem. In fact, substr don't work so... the question still here ^^" – Batfly Feb 27 '23 at 09:34

1 Answers1

0

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);
danadam
  • 3,350
  • 20
  • 18
  • Oh cool ! I tried first, last, chopped but nobody of them satisfied me ! I wasn't see the "mid" function ! So that's work, I must now convert the QByteArray slices into uint32_t and char (I found uint32 to QByteArray conversion, but not the reverse :s ) , but that's another problem, Thank you ! :D – Batfly Feb 27 '23 at 16:50