How to convert floats/doubles to raw bytes without generating garbage?

Hi!

I have a network solution using UNET LLAPI. I use my own class to send and receive bytes, and I currently use BinaryReader and BinaryWriter with a MemoryStream.
The problem is, BinaryWriter.Write(float) generates garbage (44 Bytes for each float) and I don’t want any garbage collection. This problem also occurs with double, but not with BinaryReader and/or integer, byte, char etc. BinaryFormatter is worse in every way (garbage + bytes used).

I looked around, it seems that BinaryWriter.Write(float) uses BitConverter.GetBytes(), which creates an array each time it is called. Also I believe that it’s only the Unity .NET version that does this issue.

I don’t want to use my own function (which is the same than BinaryWriter.Write(float) inside .NET v4 library) because it uses unsafe code and I want to be able to target the WebPlayer platform.

I also want a conversion without any loss of accuracy, and that doesn’t use more than 4 bytes per float once it’s converted. The speed of conversion also matters but less than accuracy and space.

Thank you.

You can use UNET NetworkWriter that is used in HLAPI, it doesn’t generate garbage and uses something like C union imitation for float-to-int conversion.

BTW, thanks for figuring out BinaryWriter generate garbage, I am using it by myself :slight_smile: