如何将浮点数组转换为byte []并返回?

时间:2011-01-08 19:45:40

标签: c# .net floating-point bytearray endianness

我有一个Floats数组,需要转换为字节数组并返回float [] ...任何人都可以帮我正确地执行此操作吗?

我正在使用bitConverter类,并发现自己无法尝试追加结果。

我这样做的原因是我可以将运行时值保存到IO流中。如果重要,目标存储是Azure页面blob。我不关心这个存储的endian,只要它输入匹配输出。

static  byte[] ConvertFloatToByteArray(float[] floats)
        {
            byte[] ret = new byte[floats.Length * 4];// a single float is 4 bytes/32 bits

            for (int i = 0; i < floats.Length; i++)
            {
               // todo: stuck...I need to append the results to an offset of ret
                ret = BitConverter.GetBytes(floats[i]);

            }
            return ret;
        }


 static  float[] ConvertByteArrayToFloat(byte[] bytes)
{ //to do }

4 个答案:

答案 0 :(得分:70)

如果您正在寻找表现,那么您可以使用Buffer.BlockCopy。很好,很简单,可能和托管代码一样快。

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

答案 1 :(得分:5)

当你将float [i]复制到字节数组中时,你没有移动位置,你应该写类似的东西

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

而不只是:

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

反函数遵循相同的策略。

答案 2 :(得分:4)

BitConverter.ToSingle(byte[] value, int startIndex)方法应该有帮助。

  

返回单精度浮点数   点数从四个字节转换而来   在一个字节的指定位置   阵列。

你可能想要(未经测试):

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();
}

编辑:非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;

答案 3 :(得分:1)

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;
}