简体   繁体   English

Byte []浮点[]到Byte []

[英]Byte[] to float[] to Byte[]

For some calculations I need to use Floats, but I have an byte[] at my disposal so I first do: 对于某些计算,我需要使用Floats,但是我有一个byte []可以使用,所以我首先要做:

Array.Copy(byteArray, floatArray, byteArray.Length);

That works great, I the do some calulations on the floats.but now I need to convert it back to an byteArray. 效果很好,我在float上做了一些计算。但是现在我需要将其转换回byteArray。 I can't use the following code, it crashes, without giving an specific error message. 我不能使用以下代码,它崩溃了,没有给出特定的错误消息。

float[] DiffernetfloatArray= new float[ byteArray];  
Array.Copy(DiffernetfloatArray, byteArray, DiffernetfloatArray.Length);

First I thought it was the size that wasn't OK, but the float array that I'm using, I increased the size by 500 just for testing, still gave me same error 首先我以为是大小不对,但是我使用的float数组只是为了测试而将大小增加了500,仍然给我同样的错误

Does anyone know how I could fix this? 有谁知道我该如何解决? Preferably answers in C# 最好用C#回答

its easier with linq: 使用linq更容易:

var byteArray = floatArray.Select(f => Convert.ToByte(f)).ToArray();
var floatArray = byteArray.Select(b => (float)Convert.ToDouble(b)).ToArray();

There's an easier way: 有一种更简单的方法:

System.BitConverter.GetBytes(float)

MSDN MSDN

可以将字节转换为浮点数,因为它适合该类型,但是通过隐式转换无法完成另一种方法-浮点数可能太大而无法容纳一个字节,因此Array.Copy将永远无法工作在这种情况下。

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

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