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

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

Now I use BlockCopy, but I need dual memory. I would like some cast.

I need to do this conversion only to send data through the socket and restore the array on the other end.

+4
source share
4 answers

Of course, the msarchet clause also makes copies. You are only talking about how .NET thinks about the memory area if you do not want to copy.

But I do not think that what you want is possible, since bytes and floats appear completely different in memory. A byte uses only bytes in memory, but a float uses 4 bytes (32 bits).

If you do not have memory requirements for storing your data, simply present the data as the type of data that you will use most in memory, and convert the values ​​that you use when you use them.

How do you want to convert a float (which can represent a value from Β± 1.5 Γ— 10-45 to Β± 3.4 Γ— 10 ^ 38) into a byte (which can represent a value from 0 to 255)?) P>

(more about her:

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

+7
source

You can use StructLayout to achieve this (from a C # question array C # unsafe value type to convert byte arrays ):

[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]); } 
+4
source

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

All Articles