本文介绍了将float []转换为byte []的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尽快从 float [] 中获取一个 byte [] 通过整个数组(可能通过强制转换)。不安全的代码是可以的。

I would like to get a byte[] from a float[] as quickly as possible, without looping through the whole array (via a cast, probably). Unsafe code is fine. Thanks!

我正在寻找一个比float数组长4倍的字节数组(字节数组的尺寸将是float数组的4倍,因为每个数组浮点数由4个字节组成)。我将其传递给BinaryWriter。

I am looking for a byte array 4 time longer than the float array (the dimension of the byte array will be 4 times that of the float array, since each float is composed of 4 bytes). I'll pass this to a BinaryWriter.

编辑
对于那些批评过早优化的批评家:
在优化之前,我已经使用ANTS探查器对此进行了基准测试。由于文件具有直写式高速缓存,并且float数组的大小恰好与磁盘上的扇区大小匹配,因此速度有了显着提高。二进制编写器包装使用 pinvoke ’d win32 API创建的文件句柄。之所以进行优化,是因为这样可以减少函数调用的次数。

EDIT:To those critics screaming "premature optimization":I have benchmarked this using ANTS profiler before I optimized. There was a significant speed increase because the file has a write-through cache and the float array is exactly sized to match the sector size on the disk. The binary writer wraps a file handle created with pinvoke'd win32 API. The optimization occurs since this lessens the number of function calls.

而且,在内存方面,此应用程序会创建使用大量内存的海量缓存。我可以分配一次字节缓冲区并重复使用多次-在此特定实例中,双倍的内存使用量等于该应用程序整体内存消耗的舍入错误。

And, with regard to memory, this application creates massive caches which use plenty of memory. I can allocate the byte buffer once and re-use it many times--the double memory usage in this particular instance amounts to a roundoff error in the overall memory consumption of the app.

所以我想这里的教训是不要做过早的假设;)

So I guess the lesson here is not to make premature assumptions ;)

推荐答案

如果您不想进行任何转换,发生这种情况,我建议使用Buffer.BlockCopy()。

If you do not want any conversion to happen, I would suggest Buffer.BlockCopy().

public static void BlockCopy(
    Array src,
    int srcOffset,
    Array dst,
    int dstOffset,
    int count
)

例如:

float[] floatArray = new float[1000];
byte[] byteArray = new byte[floatArray.Length * 4];

Buffer.BlockCopy(floatArray, 0, byteArray, 0, byteArray.Length);

这篇关于将float []转换为byte []的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:39