Search code examples
c++floating-point32-bitieee-754ofstream

C++ ofstream float encode


does anyone knows how to write an IEEE 754 single-precision (32-bit) floating-point number to an ofstream?

i'm using:

float VERSION = 0.1;
ofstream header;
header.open("a4.pbf",ios::binary);
header.write(reinterpret_cast<const char*>(&VERSION), sizeof(float));
header.close();
  • the result value: "0xCD,0xCC,0xCC,0x3D"
  • the value expected: "0x3D,0xCC,0xCC,0xCD"

thanks.


Solution

  • If you can convert the float to a uint32_t, you can use htonl to get "network" byte order which is big-endian.