6
votes

I have two QByteArray, sData and dData.

I want to copy n bytes from location x in dData i.e. &dData[x] to location y of sData i.e. &sData[y].

In C, array copy is done by memcpy(&dData[x], &sData[y], n);

How could copying above data of QByteArray be done in Qt?

3
This is not an answer, but rather an important consideration: please remember that QByteArray's raw data facility allows you to use a QByteArray object as a front for a C array. It doesn't copy anything from the said raw data, and you can't pass such QByteArray object away from the scope in which raw data exists. - d.Candela

3 Answers

6
votes

From the Qt documentation, you can use the replace function: -

QByteArray & QByteArray::replace(int pos, int len, const QByteArray & after)

Replaces len bytes from index position pos with the byte array after, and returns a reference to this byte array.

So, using the overload

QByteArray & QByteArray::replace(int pos, int len, const char * after);

sData = sData.replace(y, nBytes, dData.constData()+x);
5
votes

Besides the given answer you could also use memcpy and the QByteArray::data() member to get a pointer to the internal array. Of course you are then responsible that the size of the destination array is big enough to hold all copied data from the source array.

memcpy(dest.data() + y, src.constData() + x, n)
1
votes

If you want to copy data from index zero, there is a function for that:

sData.setRawData(dData, n);