简体   繁体   中英

Writing floats to a binary file in C++ | Equivalent of Java's DataOutputStream.writeFloat()

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<const char*>(&f), sizeof(float));

Your code seems to work well!

main.cpp:

#include <fstream>

int main() {
   std::ofstream out;
   out.open( "bin.dat", std::ios::out | std::ios::binary);
   float f = 0.5;
   out.write( reinterpret_cast<const char*>( &f ), sizeof( float ));
   out.close();
   return 0;
}

Compiling, linking:

$ g++ -o m main.cpp

Executing:

m

Listing:

$ ls
bin.dat  m.exe  main.cpp

Editing bin.dat with Notepad++:

bin.dat转储

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM