开发者

What is the Fastest way to convert byte[] to float[] and vice versa?

Which is the fastest way to convert a byte[] to float[] and vice versa (without a loop of course).

I'm using BlockCopy now, but then I need the double memory. I would like some kind of cast.

I need to do this conversion just to send the data through a socket and reconstruct 开发者_如何转开发the array in the other end.


Surely msarchet's proposal makes copies too. You are talking about just changing the way .NET thinks about a memory area, if you dont' want to copy.

But, I don't think what you want is possible, as bytes and floats are represented totally different in memory. A byte uses exactly a byte in memory, but a float uses 4 bytes (32 bits).

If you don't have the memory requirements to store your data, just represent the data as the data type you will be using the most in memory, and convert the values you actually use, when you use them.

How do you want to convert a float (which can represent a value between ±1.5 × 10−45 and±3.4 × 10^38) into a byte (which can represent a value between 0 and 255) anyway?

(see more info her about:

  • byte: http://msdn.microsoft.com/en-us/library/5bdb6693(v=VS.100).aspx
  • float: http://msdn.microsoft.com/en-us/library/b1e65aza.aspx

More about floating types in .NET here: http://csharpindepth.com/Articles/General/FloatingPoint.aspx


You can use StructLayout to achieve this (from Stack Overflow question C# unsafe value type array to byte array conversions):

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public float[] Floats;
}

static void Main(string[] args)
{
    // From bytes to floats - works
    byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
    UnionArray arry = new UnionArray { Bytes = bytes };
    for (int i = 0; i < arry.Bytes.Length / 4; i++)
        Console.WriteLine(arry.Floats[i]);
}


IEnumerable<float> ToFloats(byte[] bytes)
{
  for(int i = 0; i < bytes.Length; i+=4)
     yield return BitConverter.ToSingle(bytes, i);
}


Two ways if you have access to LINQ:

var floatarray = ByteArry.AsEnumerable.Cast<float>().ToArray();

or just using Array Functions

var floatarray = Array.ConvertAll(ByteArray, item => (float)item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜