如何在C#中将int [,]转换为byte []? 一些代码可以理解的如何在C#中将int [,]转换为byte []#
编辑:
我需要一个函数来执行以下操作:
byte[] FuncName (int[,] Input)
如何在C#中将int [,]转换为byte []? 一些代码可以理解的如何在C#中将int [,]转换为byte []#
编辑:
我需要一个函数来执行以下操作:
byte[] FuncName (int[,] Input)
由于你的问题中的细节很少,我只能猜测你想做什么......假设你想“fla tten” INTS的二维数组转换成字节的一维数组,你可以做这样的事情:
byte[] Flatten(int[,] input)
{
return input.Cast<int>().Select(i => (byte)i).ToArray();
}
注意调用Cast
:这是因为多维数组实现IEnumerable
但不IEnumerable<T>
这似乎是你错了写类型,但这里是你可能会寻找for:
byte[] FuncName (int[,] input)
{
byte[] byteArray = new byte[input.Length];
int idx = 0;
foreach (int v in input) {
byteArray[idx++] = (byte)v;
}
return byteArray;
}
我会猜测“最有可能是他的目标”。 – 2010-07-23 21:36:11
我的速度更快! – mquander 2010-07-23 21:36:43
@mquander是真的,但我的似乎符合他的需求。 – 2010-07-23 21:57:02
的BitConverter转换原始类型转换为字节数组:
byte[] myByteArray = System.BitConverter.GetBytes(myInt);
您似乎想要将2维数组的整数转换为字节。将BitConverter与必要的循环结构(例如foreach)以及您想要组合数组维度的任何逻辑组合起来。
这里的和实现,假设你正在试图序列化;不知道这是不是你想要的;它以尺寸为前缀,然后使用基本编码的每个单元格:
public byte[] Encode(int[,] input)
{
int d0 = input.GetLength(0), d1 = input.GetLength(1);
byte[] raw = new byte[((d0 * d1) + 2) * 4];
Buffer.BlockCopy(BitConverter.GetBytes(d0), 0, raw, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(d1), 0, raw, 4, 4);
int offset = 8;
for(int i0 = 0 ; i0 < d0 ; i0++)
for (int i1 = 0; i1 < d1; i1++)
{
Buffer.BlockCopy(BitConverter.GetBytes(input[i0,i1]), 0,
raw, offset, 4);
offset += 4;
}
return raw;
}
这使得我的头很难受。你需要指定更多的东西 - 更重要的是我甚至无法列出所有东西!让我们从“你试图解决什么问题到底是什么?”开始吧。 – 2010-07-23 21:26:12
添加了一些更多的细节。 – mouthpiec 2010-07-23 21:31:02
什么是'[,] int'和'[] byte'应该是什么意思?这在C#中不存在,你可能是指'int [,]'和'byte []'... – 2010-07-23 21:31:29