PDA

View Full Version : QDataStream writing wrong values



alok9871
21st March 2013, 03:20
Hi

I wish to write something onto a data file. I thought of using QDataStream, but it tens to give me wrong output.



QFile file("file.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out.setByteOrder(QDataStream::LittleEndian);
//out << QString("the answer is"); // serialize a string
int x = 54;
out << (qint32)x;
out.device()->close();


I was expecting an output of 54. Itself it shouwing me its char value = 6; even with other numbers.

Please let me know how to address this problem

Thanks

Regards
Alok

lanz
21st March 2013, 06:04
If you need text output you should use http://qt-project.org/doc/qt-4.8/qtextstream.html instead.

QDataStream outputs data as sequence of bytes, not printable characters.

ChrisW67
21st March 2013, 06:34
Please let me know how to address this problem
There is no problem. QDataStream is outputting exactly what you asked it to. You have a 32-bit unsigned integer with the value 54 and you have asked for output in LittleEndian order. The integer is 4 bytes 0x00000036, and QDataStream outputs them in reverse order. You get 4 bytes in the file, the first is 54 decimal (0x36) followed by 3 zero bytes. Treated as text this is equivalent to the C string "6".



const int num = 54;

QFile out("out.txt");
if (out.open(QIODevice::WriteOnly) {
QTextStream s(&out);
s << num;
}

Also look at QString::number(), QByteArray::number() etc.

alok9871
21st March 2013, 06:54
Thank you both for your amazing answers. Thanks Chris for the explanation. Learned something very useful.