Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Pedro77 Avatar asked Dec 22 '22 10:12

Pedro77


2 Answers

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

like image 85
Erik A. Brandstadmoen Avatar answered Dec 24 '22 01:12

Erik A. Brandstadmoen


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]);
}
like image 28
Philipp Schmid Avatar answered Dec 24 '22 01:12

Philipp Schmid