How to write a raw QByteArray or manipulate the QByteArray

2.2k views Asked by At

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 =)

1

There are 1 answers

0
Eric Lemanissier On

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];