c++matlabbinaryieee

C++ Read Binary File with "ieee-be" machinefmt


I basically try to convert Matlab Code to C++, reading a binary file I do not really know how it looks like.

The Matlab Code is simplified as follows:

x=zeros(48,32);    
fid=fopen('pres_00.bin','r','ieee-be');
fseek(fid,ipos,'bof');
x(1:4:48,:)=fread(fid,[12,32],'single');

in the end we basically get double numbers in the x array (row 1, 5,..)

How can I read the *.bin file in C++? I tried:

file1.seekg(0, ios::end);
int length = file1.tellg();
file1.seekg(ipos, ios_base::beg);
lenght = lenght - ipos;

char * buffer = new char[length];

file1.read(buffer, length);
double* double_values = (double*)buffer;
double test = double_values[0];
file1.close();

Sadly "test" is not similar to the number matlab is encoding out of the binary file. How can I implement the information with the ieee-be encoding into c++? Unfortunately I'm not that familiar with binary files...

Cheers and thanks for your help!

//edit:

Maybe it helps: In my case

ipos = 0
the first hex row (offset0) (32) : 
44 7C CD 35 44 7C AD 89 44 7C E9 F2 44 7D F7 10 44 7D 9C F9 44 7B F9 E4 44 7B 3E 1D 44 7B 6C CE

ANSI: D|Í5D|.‰D|éòD}÷.D}œùD{ùäD{>.D{lÎ

First value in Matlab: 1.011206359863281e+03

What my Code reads in buffer: D|Í5D|-‰.D|éòD}÷.\x10D}œùD{ùäD{>\x1dD{lÎ......
double test = -4.6818882332480884e-262

Solution

  • There are two parts to this problem. First, the representation is IEEE 32 bit floating point; since most processors use IEEE floating point, all you need is a simple cast to do the conversion. This won't be portable to all processors though. The second part is the be in the ieee-be specification, it means that the bytes are stored big-endian. Since many processors (i.e. Intel/AMD) are little-endian, you need to do a byte swap before the conversion.

    void byteswap4(char *p)
    {
        std::swap(p[0], p[3]);
        std::swap(p[1], p[2]);
    }
    
    float to_float(char *p)
    {
        return *((float*)p);
    }
    

    See it in action: https://ideone.com/IrDEJF