[英]Writing floats to a binary file in C++ | Equivalent of Java's DataOutputStream.writeFloat()
我正在将一些代码从Java移植到C ++,并且需要将浮点数写入二进制文件。 在Java中,我使用DataOutputStream.writeFloat()
。 我如何用C ++做到这一点?
我试过这个方法,但它不起作用:
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));
你的代码似乎运行良好!
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;
}
编译,链接:
$ g++ -o m main.cpp
执行:
m
清单:
$ ls
bin.dat m.exe main.cpp
使用Notepad ++编辑bin.dat:
Java的默认行为是以big endian编写文件(以及流传输到IO的任何其他数据)。 C ++以本机格式写入文件。 在标准的x86派生的PC上,native是little endian,所以对于0.5,你得到:
0x00 00 00 3f
在C ++中
和
Java中的0x3f 00 00 00
。
为了编写可由两者读取的文件,您必须确定输出文件将使用哪个字节序,并且其中一个程序必须反转其字节序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.