How do I convert an array of floats to a byte[] and back?

Solution 1:

If you're looking for performance then you could use Buffer.BlockCopy. Nice and simple, and probably about as fast as you'll get in managed code.

var floatArray1 = new float[] { 123.45f, 123f, 45f, 1.2f, 34.5f };

// create a byte array and copy the floats into it...
var byteArray = new byte[floatArray1.Length * 4];
Buffer.BlockCopy(floatArray1, 0, byteArray, 0, byteArray.Length);

// create a second float array and copy the bytes into it...
var floatArray2 = new float[byteArray.Length / 4];
Buffer.BlockCopy(byteArray, 0, floatArray2, 0, byteArray.Length);

// do we have the same sequence of floats that we started with?
Console.WriteLine(floatArray1.SequenceEqual(floatArray2));    // True

Solution 2:

You are not moving the position when you copy the float[i] into the byte array, you should write something like

Array.Copy(BitConverter.GetBytes(float[i]),0,res,i*4);

instead of just:

ret = BitConverter.GetBytes(floats[i]);

the inverse function follow the same strategy.

Solution 3:

There's the BitConverter.ToSingle(byte[] value, int startIndex) method that should help out here.

Returns a single-precision floating point number converted from four bytes at a specified position in a byte array.

Your probably want something like (untested):

static float[] ConvertByteArrayToFloat(byte[] bytes)
{
    if(bytes == null)
        throw new ArgumentNullException("bytes");

   if(bytes.Length % 4 != 0)
        throw new ArgumentException
              ("bytes does not represent a sequence of floats");

    return Enumerable.Range(0, bytes.Length / 4)
                     .Select(i => BitConverter.ToSingle(bytes, i * 4))
                     .ToArray();
}

EDIT: Non-LINQ:

float[] floats = new float[bytes.Length / 4];

for (int i = 0; i < bytes.Length / 4; i++)
    floats[i] = BitConverter.ToSingle(bytes, i * 4);

return floats;

Solution 4:

static float[] ConvertByteArrayToFloat(byte[] bytes)
{
    if(bytes.Length % 4 != 0) throw new ArgumentException();

    float[] floats = new float[bytes.Length/4];
    for(int i = 0; i < floats.Length; i++)
    {
        floats[i] = BitConverter.ToSingle(bytes, i*4);
    }

    return floats;
}