C#中如何将浮点数组转换为字节数组?

我想将浮点数组转换为字节数组,以通过套接字将其发送到 python 脚本。(我正在 Unity 引擎中执行此操作)。


我试过:


float[] myArray = {0.0f, 0.0f, 0.0f};


int len = myArray.Length;

byte[] bytes = new byte[len];

int x = 0;


foreach(float f in bytes){

  byte[] t = System.BitConverter.GetBytes(f);

  for(int y = 0; y<4); y++){

    bytes[y + x] = t[y];

    x += 4;

  }

}

输出是这样的:

Assets\PlayerScript.cs(106,27): 错误 CS1002: ; 预期的

Assets\PlayerScript.cs(106,33): 错误 CS1002: ; 预期的

Assets\PlayerScript.cs(106,33): 错误 CS1513: } 预期

我不习惯使用 c# 并且无法让它工作...我还查看了其他一些 stackoverflow 代码,但这并没有真正帮助。


函数式编程
浏览 168回答 1
1回答

莫回无

尝试以下操作:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;float[] myArray = {0.0f, 0.0f, 0.0f};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int len = myArray.Length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;List<byte> bytes = new List<byte>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach (float f in myArray)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte[] t = System.BitConverter.GetBytes(f);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bytes.AddRange(t);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte[] byteArray = bytes.ToArray();
打开App,查看更多内容
随时随地看视频慕课网APP