PDA

View Full Version : Reading binary file with maltlab format



Lumbricus
26th November 2015, 13:26
Hey guys,

i want to read a binary file which has been read with matlab with this format; 8x double in one line, varying number of lines depending on the file.

in matlab i can read it like this:

fid=fopen("filepath),'r')
initial_state = fread(fid, [8 inf],'double'); #


from the matlab documentation i found that a matlab double = 64Bits or 8Bytes

i am using a 64-bit version of qt. This is how i tried to read the file:



QFile binary("filepath.bin");
binary.open(QIODevice::ReadOnly);
QDataStream in(&binary);
in.setFloatingPointPrecision(QDataStream::DoublePr ecision); //64-bit
double d1,d2,d3,d4,d5,d6,d7,d8;
in >> d1 >> d2 >> d3 >> d4 >> d5 >> d6 >> d7 >>d8;
qDebug() << d1 << d2 << d3 << d4 << d5 <<d6 << d7 <<d8;


From qt documentation:

QDataStream & QDataStream::operator>>(double & f)

i think this is what i need but i cant figure out how to use it. The output i am getting are not the output that matlab is reading. can someone point me in the right direction? cheers!

anda_skoa
26th November 2015, 14:14
Matlab is unlikely using QDataStream so you don't use it either.

Cheers,
_

ChrisW67
26th November 2015, 19:45
If the stored byte order is the same as you machine architecture.


Q_ASSERT(sizeof(double)==8);
QFile binary("filepath.bin");
if( binary.open(QIODevice::ReadOnly) ) {
double values[8];
qint64 bytes = binary.read(static_cast<char *>(values), 64);
if (bytes == 64) {
for (int i = 0; i < 8; ++i)
qDebug() << values[i];
}
}

If the byte order is different then you have a byte swapping exercise to do.

With a primitive type (i.e. Known size) you might be able to use QDatastream but you still need to know the byte order and set the stream accordingly. That is not really QDataStream's purpose though.

Lumbricus
4th December 2015, 16:06
Thx guys, i took anda's tip and used standard c++ fopen and fread and reverse engineered the code that wrote the binary file to find out what format it has.

anda_skoa
5th December 2015, 11:19
You could have still used QFile and its read methods, just using QDataStream was too much :)

Cheers,
_