Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first bytes from QByteArray

Tags:

qt

qbytearray

I want to write a function in which QByteArray is input to the function. I want to remove some header from receive data and store it into global QByteArray.

void abc::CopyData(const QByteArray &data)
{
    switch(RequestPacketCount)
    {
        case REQUEST_FIRST_PACKET:
        {
            ByteArrayData = data;
        }
            break;
        case REQUEST_SECOND_PACKET:
        case REQUEST_THIRD_PACKET:
            ByteArrayData.append(data);
    }
}

I want to remove 'n' no. of byte from start of 'data' and store remaining data into 'ByteArrayData'

Thanks in advance.

like image 511
beparas Avatar asked Mar 19 '14 05:03

beparas


2 Answers

What you seem to want is simply copy the original array and use remove;

ByteArrayData = data;
ByteArrayData.remove(0, n);            // Removes first n bytes of ByteArrayData,
                                       // leaving data unchanged

Since a QByteArray is implicitly shared, the construction of the copy takes constant time, and the modification (deletion) is what will make the actual copy when needed.

To append efficiently, you can just use data to get to the byte array, and append the part you want. That will prevent un-necessary temporary objects. That would look something like;

ByteArrayData.append(data.data() + n, data.size() - n);
like image 78
Joachim Isaksson Avatar answered Sep 17 '22 22:09

Joachim Isaksson


You can use QByteArray::mid:

ByteArrayData = data.mid(n);
//...
ByteArrayData.append(data.mid(n));
like image 21
Pavel Strakhov Avatar answered Sep 19 '22 22:09

Pavel Strakhov