PDA

View Full Version : Save 4 Integers in a QByteArray without memcpy



GonzoFist
17th May 2010, 16:29
Hi,

I got a QByteArray called mBuffer, and I want to put 4 Integers in it.
I did this with the append function of QByteArray.
But if I for Example put these values (2,42,7,9224) in it, in my Buffer stays 24279224.
But I want that 00'00'00'02'00'00'00'2A'00'00'00'07'00'00'24'08 are in my Buffer.
00'00'00'02 for 2
00'00'00'2A for 42
00'00'00'07 for 7
00'00'24'08 for 9224

Those 00 stand for each Byte, and I got 4 for each Integer.
I think oneway would be to use memcpy, but for this I have to convert my Integer in Char[4] array, and then memcpy it to the Buffer. But I hope there is a more proper Solution.

victor.fernandez
17th May 2010, 17:08
int values[] = { 2, 42, 7, 9224 };
QByteArray data;

for(int i = 0; i < 4; i++) {
int number = values[i];
data += QByteArray( (const char*) &number, sizeof(int));
}

Anyway, if you want to store data into a file or something, it's better to use QDataStream because it's independent of the byte order.

GonzoFist
17th May 2010, 18:06
Thank you,
For my Programm i didnt use the for-thing, i directly took my variable. But this isnt this relevant.



mBuffer += QByteArray((const char*)&mSerial,sizeof(int));

Ehm but I really dont understand how this works.
with
(const char*)&mSerial
I get a pointer to the adress my integer, right?

And with QByteArray(const char*,4) I make a QByteArray with 4 Bytes which are taken from the adress on which the pointer shows?

ChrisW67
17th May 2010, 23:15
And with QByteArray(const char*,4) I make a QByteArray with 4 Bytes which are taken from the adress on which the pointer shows?
Your assessment seems right to me (at least on machines with 4-byte ints).

The order of the bytes in the QByteArray will depend on the architecture of the machine, may not be the order you are expecting, and may not be portable to other architectures.