简体   繁体   English

将byte []转换为float []的最快方法是什么,反之亦然?

[英]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). 这是将byte []转换为float []的最快方法,反之亦然(当然没有循环)。

I'm using BlockCopy now, but then I need the double memory. 我现在正在使用BlockCopy,但后来我需要双内存。 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. 毫无疑问,msarchet的提议也会复制。 You are talking about just changing the way .NET thinks about a memory area, if you dont' want to copy. 你正在谈论的只是改变.NET思考内存区域的方式,如果你不想复制的话。

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). 一个字节在内存中只使用一个字节,但浮点数使用4个字节(32位)。

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? 您想如何将浮点数(可以表示介于±1.5×10-45和±3.4×10 ^ 38之间的值)转换为一个字节(可以表示0到255之间的值)?

(see more info her about: (查看更多关于她的信息:

More about floating types in .NET here: http://csharpindepth.com/Articles/General/FloatingPoint.aspx 有关.NET中浮动类型的更多信息,请访问: 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来实现此目的(从Stack Overflow问题C#unsafe值类型数组到字节数组转换 ):

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

Two ways if you have access to LINQ : 如果您有权访问LINQ,有两种方法:

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

or just using Array Functions 或者只使用数组函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM