PDA

View Full Version : reading 4-bytes integer from binary file



maka
7th May 2009, 12:35
Hello, people.

Нelp me please with subject.
Im a beginner in QT. It looks like QT has only 8/16/32/64-bytes integer. Is there is a way to read 4-bytes integer from binary file in QT?

Thank you!

Ginsengelf
7th May 2009, 13:04
Those numbers are bits, not bytes.

Ginsengelf

faldzip
7th May 2009, 13:18
And 8 bits is 1 byte so you are looking for 32-bit integer which is exactly 4-byte integer. In Qt it's qint32.

maka
7th May 2009, 14:08
Oh! Im just an idiot!
Thank you for illumination.:)

maka
8th May 2009, 05:13
Ok. Illumination is good but the code still doesnt work.


QFile Source_file;
Source_file.setFileName("D:/Dela/QTtest/Begin.rg2");
if (Source_file.open(QIODevice::ReadOnly)) {
QDataStream data (&Source_file);
// data.setByteOrder(data.LittleEndian);
qint32 intb;
data>>intb;
qDebug()<<intb;
}
Source_file.close();

I have a value of intb different from that was saved in file. I tried both LittleEndian and BigEndian.
The file was made in Delphi. It reads well in Delphi and in Java.

What the problem may be in?

Thank you.

wysota
8th May 2009, 08:22
What the problem may be in?

The problem is in using QDataStream. It's a serialization mechanism that stores (and expects) some additional data in the stream. If you just want to read 4 bytes from the file, use QIODevice::read on the QFile object and cast the data to a type of your choice.

maka
8th May 2009, 10:28
The problem is in using QDataStream. It's a serialization mechanism that stores (and expects) some additional data in the stream. If you just want to read 4 bytes from the file, use QIODevice::read on the QFile object and cast the data to a type of your choice.

Thanks for reply!

Now Im trying to do this:


QFile Source_file;
Source_file.setFileName("D:/Dela/QTtest/Begin.rg2");

if (Source_file.open(QIODevice::ReadOnly)) {
qint32 intb;
QByteArray bar;
bar = Source_file.read(4);
bool ok;
intb = bar.toInt(&ok,0);
qDebug()<<intb;

}
Source_file.close();

Still have wrong result. I suspect becouse of endianity. Is there is a way to fix it avoiding manual changing of bytes order?

wysota
8th May 2009, 12:17
toInt() does something completely different. What you need to do is something like this:

QByteArray ba = file.read(4);
qint32 x;
memcpy(&x, ba.constData(), 4);

maka
12th May 2009, 06:57
It works.

Thank you very much!