Pedro77
Pedro77

Reputation: 5294

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.

Upvotes: 4

Views: 3139

Answers (4)

Philipp Schmid
Philipp Schmid

Reputation: 5828

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

Upvotes: 4

msarchet
msarchet

Reputation: 15232

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

Upvotes: -1

Evan Machusak
Evan Machusak

Reputation: 617

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

Upvotes: 0

Erik A. Brandstadmoen
Erik A. Brandstadmoen

Reputation: 10588

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:

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

Upvotes: 7

Related Questions