0

I defined a QIODevice (especially a QTcpSocket) and would like to write a string as raw format. I describe my wishes with the following example:

char* string= "Hello World";

QByteArray bArray;
QDataStream stream(&bArray, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_4_6);
stream << string;

QFile file("Output.txt");
file.open(QIODevice::WriteOnly);
file.write(bArray);
file.close();

If I open the Output.txt in the Hex Editor I get the following result:

00 00 00 0C  48 65 6C 6C 6F 20 57 6F 72 6C 64  00

00 00 00 0C = 4bytes (length of the following massage)
48 65 6C 6C 6F 20 57 6F 72 6C 64 = 11bytes (the string "Hello World")
00 = an one empty byte

But thats not what I want. Is it possible to cut the lenth from 4bytes to just 2bytes? Or is it possible to grab just the string and define my own length of 2bytes instead?

The reason why I am asking is that I would like to send a message to a server. But the server accepts just packets in the following format:

00 0C  48 65 6C 6C 6F 20 57 6F 72 6C 64

00 0C = 2bytes
48 65 6C 6C 6F 20 57 6F 72 6C 64 = 11bytes

Any help would be great =)

3ef9g
  • 781
  • 2
  • 9
  • 19
  • Well, `QByteArray` has `[]` operator, so you can use it as a regular array, just move data 2 bytes to the "left" and resize the array to trim it at the end. Or just copy it into another byte array while skipping the first 2 bytes. – dtech Nov 28 '14 at 22:08

1 Answers1

0

If you need a special serialization format that do not match QDataStream's serialization, then you should code it yourself, instead of relying on QDataStream and modifying the result. it could be something like that:

QByteArray byteArray;
...
QDataStream stream(..);
...
byteArray.chop(1); // to remove the 0 character at the end of c string
stream << quint16(byteArray.size()); // to write the size on 2 bytes
for(int i = 0; i < byteArray.size(); i++)
    stream << byteArray[i];
Eric Lemanissier
  • 357
  • 2
  • 15