QDataStream writing wrong values
Hi
I wish to write something onto a data file. I thought of using QDataStream, but it tens to give me wrong output.
Code:
//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
Re: QDataStream writing wrong values
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.
Re: QDataStream writing wrong values
Quote:
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".
Code:
const int num = 54;
s << num;
}
Also look at QString::number(), QByteArray::number() etc.
Re: QDataStream writing wrong values
Thank you both for your amazing answers. Thanks Chris for the explanation. Learned something very useful.