Conversion from binary data to float

I have a file in binary format, with float numbers, so I understand that each 4 bytes there is a float number. I have this example (open in hexadecimal editor): 00 00 40 40. This represents the number 3.0E0 (i.e., 3). When reading the binary file (open in mode read binary), how can I convert the data into float numbers? I hesitate about getting 4 bytes at once and convert into binary and from that extract the sign, the mantisa, the exponent... or there is a much easier way to get the data and make a printf(%f) which shows in the screen the numbers (in this case, 3.0E0 or 3). Thanks!!!

PS: I am also very confused about the order of the bytes, because according to the standard Float (IEEE754 Single precision 32-bit), it should be 0x40400000
so I am thinking that this is an issue with little and big endian, right?
Last edited on
I am also very confused about the order of the bytes, because according to the standard Float (IEEE754 Single precision 32-bit), it should be 0x40400000
so I am thinking that this is an issue with little and big endian, right?
Right. It looks like file was written on platform using little-endian format (like x86 platform).

You can read information from binary file directly to the variable (assuming binary representations of source and target are same, which it looks like the case here):
1
2
3
//std::ifstream input(/*...*/, std::ios::binary)
float d;
input.read(reinterpet_cast<unsigned char*>(&d), sizeof(float));
Thank you very much. I just used fread (&readData, sizeof (float), 1, f ) and it worked like a charm. I just don't understand anything. So if I would use the compiled source in a Linux environment, with the same binary file, it would fail because of the little-endian format? And why this is not indicated in the fread command? This is too difficult for me.
in a Linux environment, with the same binary file, it would fail because of the little-endian format?
If it uses IEEE floats and executes on x86 platform, everything will be all right.

And why this is not indicated in the fread command?
What is not indicated? fread reads raw binary data. What in this data and how it is organised is not in it competence. You should care about any possible implementation differences yourself if you decided (for some reason) to use binary data.

For example it is a good idea to specify and store all binary data in specified byte order. You have to do this manually (or using POSIX functions)
Topic archived. No new replies allowed.