Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QbyteArray data copy

Tags:

qt

qbytearray

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?

like image 541
beparas Avatar asked Apr 01 '14 08:04

beparas


3 Answers

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);
like image 138
TheDarkKnight Avatar answered Nov 07 '22 09:11

TheDarkKnight


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)
like image 37
Matthias247 Avatar answered Nov 07 '22 08:11

Matthias247


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

sData.setRawData(dData, n);
like image 1
Mubin Icyer Avatar answered Nov 07 '22 07:11

Mubin Icyer