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

问题描述 投票:0回答:5

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

我正在使用 bitConverter 类,发现自己在尝试附加结果时陷入困境。

我这样做的原因是为了可以将运行时值保存到 IO 流中。如果重要的话,目标存储是 Azure Page blob。我不关心它存储在什么字节序中,只要它的输入与输出匹配即可。

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 }
c# .net floating-point arrays endianness
5个回答
120
投票

如果您正在寻找性能,那么您可以使用

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

7
投票

这里有

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;

6
投票

当您将 float[i] 复制到字节数组时,您并没有移动位置,您应该编写类似的内容

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

而不仅仅是:

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

反函数遵循相同的策略。


2
投票
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;
}

0
投票

您可以通过联合直接以字节形式访问浮点(或其他)数组,并完全避免使用 BitConverter。有关 C# 联合的更多信息,请参见此处 如何使用 C# 中的属性创建 C/C++ 联合

using System.Runtime.InteropServices;

// create an array of 100 floats and set values
const int floatCount = 100;
var arrayUnion = new ArrayUnion(floatCount * sizeof(float));
for (var n = 0; n < floatCount; ++n)
    arrayUnion.floatArray[n] = n;

// write the byte array to a file
var filename = "c:/temp/testwrite.bin";
using (FileStream stream = new(filename, FileMode.Create, FileAccess.Write)) {
    stream.Write(arrayUnion.byteArray, 0, arrayUnion.byteArray.Length);
    }

// read the byte array back and write out the float values
using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
    stream.Read(arrayUnion.byteArray, 0, arrayUnion.byteArray.Length);

    for (var n = 0; n < floatCount; ++n)
        Console.WriteLine(arrayUnion.floatArray[n]);
    }

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct ArrayUnion(int byteCount) {
    [System.Runtime.InteropServices.FieldOffset(0)]
    public byte[] byteArray = new byte[byteCount];

    [System.Runtime.InteropServices.FieldOffset(0)]
    public float[] floatArray;
    }
© www.soinside.com 2019 - 2024. All rights reserved.