Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read/write raw data with QDataStream

Tags:

c++

qt

I am fairly new to QDataStream and Socket programming, and what I want to do is to simply send a quint32 header value (four bytes) from client to host. But I am having some trouble with QDataStream.

QByteArray data;
QDataStream ds(&data, QIODevice::ReadWrite);
int a = htonl(32);
char *head = (char*)&a;
for(int i=0;i<4;i++)
    qDebug() << QString::number(int((head[i]&0xff))+0x100, 16) << " ";
qDebug() << endl;

here, the output is "100 100 100 120", which is what I want. Then I try to write it into data stream.

ds.writeRawData(head, 4);
char *buffer = new char[4];
ds.readRawData(buffer, 4);
for(int i=0;i<4;i++)
    qDebug() << QString::number(int((buffer[i]&0xff))+0x100, 16) << " ";
qDebug() << endl;

But here the output here is "100 100 100 100"

Am I having some misunderstanding about the usage of QDataStream?

like image 873
TimC Avatar asked Jan 30 '12 03:01

TimC


1 Answers

You should reset the position of the stream device by calling ds.device()->reset(); before you attempt to read the data with ds.readRawData().

ds.readRawData() will return the number of bytes that were read. If you check it, it is probably returning 0.

like image 134
Arnold Spence Avatar answered Oct 02 '22 19:10

Arnold Spence