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

4

1 回答 1

0

如果你需要一个特殊的序列化格式与 QDataStream 的序列化不匹配,那么你应该自己编码,而不是依赖 QDataStream 并修改结果。它可能是这样的:

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];
于 2014-11-29T08:54:02.827 回答