如何在C#中将int 转换为byte

如何在C#中将int [,]转换为byte []? 一些代码将不胜感激

编辑:

我需要一个函数来执行以下操作:

byte[] FuncName (int[,] Input) 

由于您的问题中的细节非常少,我只能猜测您要做的事情……假设您想要将2D数组的整数“展平”为1D字节数组,您可以执行以下操作:

 byte[] Flatten(int[,] input) { return input.Cast().Select(i => (byte)i).ToArray(); } 

注意对Cast的调用:那是因为多维数组实现IEnumerable而不是IEnumerable

看起来你写错了类型,但这里有你可能正在寻找的东西:

 byte[] FuncName (int[,] input) { byte[] byteArray = new byte[input.Length]; int idx = 0; foreach (int v in input) { byteArray[idx++] = (byte)v; } return byteArray; } 

这是一个假定您正在尝试序列化的实现; 不知道这是不是你想要的; 它为维度添加前缀,然后每个单元格使用基本编码:

 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; } 

BitConverter将原始类型转换为字节数组:

 byte[] myByteArray = System.BitConverter.GetBytes(myInt); 

您似乎希望将2维int数组转换为字节。 将BitConverter与必需的循环结构(例如foreach)以及您想要组合数组维度的任何逻辑相结合。