la******@yahoo.com schrieb:

So I am converting some matlab code to C++. I am stuck at one part of

the code. The matlab code uses fread() to read in to a vector a file.

It's a binary file. The vector is made up of floats, which in matlab

is 32 bits. How do I get this binary file in to floats in c++?

I try reading the file using the ifstream>>myFloat. But nothing ever

goes in to the float. So the closest I have come is having 4 unsigned

char store the binary data. But from there I don't know how to get

it in to a float? When I try to do:

myFloat<<myChar1<<8;

myFloat<<myChar2<<8;

myFloat<<myChar3<<8;

myFloat<<myChar4<<8;

I don't get the correct answer.

myFloat being the float and myChar1, myChar2, myChar3, myChar4 being

the 4 unsigned chars that have the binary data from the file in them.

Using a hex editor I have verified that the four unsigned chars do have

the correct value in them.

Does matlab represent floats different?

I don`t know how float is implemented in matlab. In my implementation of

C (C++) it is implemented the following way (IEEE):

float: 1Bit Sign/ 8Bits Exponent / 23Bits Mantisse = 32 Bits

Maybe this split ist different in matlab (in ammount of bits per

component, and the order of the components) ... but i donīt think so

In pure C i would solve it the following way:

matlab float -> bytes-> C/C++ float

in C/C++ you can do then

union {

float mycfloat;

unsigned char frommatlab [sizeof(float)];

} conversion;

and write the bytes you got from matlab into conversion.frommatlab[...]

and read out the float with conversion.mycfloat

regards marcas