Best way to serialize a Float in java to be read by C++ app?

后端 未结 3 2000
[愿得一人]
[愿得一人] 2021-01-06 05:16

I need to serialize a java Float to be read by an application written in C++ over Socket comms. Is there a standard for this? It would be easiest to use the method floatToIn

3条回答
  •  执念已碎
    2021-01-06 05:53

    Use Float.floatToIntBits() (or Float.floatToRawIntBits() if you want to preserve NaN values) to convert the float to an integer. floatToIntBits() is specified to return the integer in IEEE 754 format, which is the format used by virtually all C/C++ implementations. You should then convert the integer into a byte array in network byte order (big-endian), which you can then safely serialize to a file, socket, byte stream, etc.:

    int floatBits = Float.floatToIntBits(myFloat);
    byte floatBytes[] = new byte[4];
    floatBytes[0] = (byte)(floatBits >> 24);
    floatBytes[1] = (byte)(floatBits >> 16);
    floatBytes[2] = (byte)(floatBits >> 8);
    floatBytes[3] = (byte)(floatBits);
    

提交回复
热议问题