6

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?

Adrian W
  • 4,563
  • 11
  • 38
  • 52
beparas
  • 1,927
  • 7
  • 24
  • 30
  • 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 Apr 29 '19 at 10:44

3 Answers3

6

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);
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
6

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)
Matthias247
  • 9,836
  • 1
  • 20
  • 29
-1

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

sData.setRawData(dData, n);
Mubin Icyer
  • 608
  • 1
  • 10
  • 21
  • 5
    FYI: This answer is misleading because the data is NOT copied. The Qt documentation for setRawData states: "The bytes are not copied. The QByteArray will contain the data pointer. The caller guarantees that data will not be deleted or modified as long as this QByteArray and any copies of it exist that have not been modified." – K9spud Jul 09 '19 at 05:18