Remove first bytes from QByteArray

beparas picture beparas · Mar 19, 2014 · Viewed 15.2k times · Source

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.

Answer

Joachim Isaksson picture Joachim Isaksson · Mar 19, 2014

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);