I'm porting some code from Java to C++ and need to write floats to a binary file. In Java I use DataOutputStream.writeFloat(). How do I do it in C++?
I tried this method but it doesn't work:
std::ofstream out;
out.open(somePath, std::ios::out | std::ios::binary);
float f = 0.5;
out.write(reinterpret_cast(&f), sizeof(float));
解决方案
Java's default behaviour is to write files (and any other data streamed to IO) in big endian. C++ writes files in native format. On a standard x86-derived PC native is little endian, so for 0.5 you get:
0x00 00 00 3f in C++
and
0x3f 00 00 00 in Java.
In order to write files that can be read by both, you will have to establish which endian the output files will use and one of the programs will have to reverse their endian.