首页 > 解决方案 > 如何在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 代码,但这并没有真正帮助。

标签: c#arraysunity3d

解决方案


尝试以下:

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

           int len = myArray.Length;
           List<byte> bytes = new List<byte>();

           foreach (float f in myArray)
           {
               byte[] t = System.BitConverter.GetBytes(f);
               bytes.AddRange(t);
           }
           byte[] byteArray = bytes.ToArray();

推荐阅读