c# - 如何在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 代码,但这并没有真正帮助。
解决方案
尝试以下:
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();
推荐阅读
- python - 使用 win32com.client 从 excel 中删除过滤器
- c++ - 如何在 react-native 中使用 c++?
- directx-11 - 将 CONST D3DMATRIX 转换为 XMMATRIX
- redis - Redis 流 NOMKSTREAM
- bfg-repo-cleaner - 如何使用 bfg 恢复误删除的对象?
- angular - 如何在类型脚本中将胖箭头函数替换为没有胖箭头函数
- javascript - AJAX 在我尝试将数据发布到的 url 上显示错误
- google-apps-script - Google Drive:有些用户有明确的权限,有些用户有继承的权限。我能说出区别吗?
- dialogflow-cx - 将 Dialogflow CX 管道导入 Google Data Studio
- inno-setup - 使用xdelta(IsDone,运行bat)在inno setup中修补文件的最佳和正确方法是什么