The general method has been answered multiple times before, but I have a problem with my implementation which fails, and am looking to see if a kind reader can spot where I'm going wrong.
Code and test are;
 [TestMethod]
    public void FloatConversion()
    {
        // Set up some test data
        int repetitions = 100000;
        Random rand = new Random();
        float[] testSetOfFloats = new float[repetitions];
        for (int count = 0; count < repetitions; count++)
        {
            testSetOfFloats[count] = rand.NextFloat(0, float.MaxValue);
        }
        // Convert the floats into a byte array
        byte[] floatsAsByteArray = new byte[repetitions * 4]; // 4 bytes for a Single
        for (int count = 0; count < repetitions; count++)
        {
            byte[] floatAsBytes = BitConverter.GetBytes(testSetOfFloats[count]);
            floatAsBytes.CopyTo(floatsAsByteArray, count * 4);
        }
        // Convert the byte array to a Unicode string
        string serialisedByteArray = System.Text.Encoding.Unicode.GetString(floatsAsByteArray);
        // ... Do some work, store the string, re-read the string, then ...
        // Convert the unicode string back into a byte array
        byte[] deserializedByteArray = System.Text.Encoding.Unicode.GetBytes(serialisedByteArray);
        // Convert the byte array back into an array of floats
        float[] deserializedFloats = new float[repetitions];
        for (int count = 0; count < repetitions; count++)
        {
            int offset = count * 4;
            deserializedFloats[count] = BitConverter.ToSingle(deserializedByteArray, offset);
        }
        for (int count = 0; count < repetitions; count++)
        {
            // This will fail - but many will pass the test.
            Assert.IsTrue(deserializedFloats[count] == testSetOfFloats[count]);
        }
    }
The only non-standard method is an extension to Random NextFloat() which just returns a random Single from the passed range of values.
 
     
    