【问题标题】:Converting a two dimensional int array to a byte array将二维 int 数组转换为字节数组
【发布时间】:2015-05-27 13:55:12
【问题描述】:


我想将二维 int 数组转换为字节数组。最简单的方法是什么?
例子:

int[,] array = new int[2, 2] { { 2, 1 }, { 0, 1 } };

如何将array 转换为byte[]?在您的回答中,请同时包含与之相反的功能。 (如果有将int[,] 转换为byte[] 的功能,请告诉我如何将byte[] 转换为int[,]
如果您问自己为什么需要这样做:我需要通过 TCP 客户端向服务器发送int[,],然后向客户端发送响应
PS:我考虑过创建一个[Serializeable] 类,其中将包含int[,],然后将该类序列化为一个文件并发送该文件,在服务器端我将反序列化该文件并从那里获取数组。但我认为这需要更多的资源才能做到这一点,然后将其转换为byte[]
感谢您的帮助! :)

【问题讨论】:

    标签: c# arrays type-conversion byte bytearray


    【解决方案1】:

    简答:Buffer.BlockCopy.

    public static byte[] ToBytes<T>(this T[,] array) where T : struct
    {
      var buffer = new byte[array.GetLength(0) * array.GetLength(1) * System.Runtime.InteropServices.Marshal.SizeOf(typeof(T))];
      Buffer.BlockCopy(array, 0, buffer, 0, buffer.Length);
      return buffer;
    }
    public static void FromBytes<T>(this T[,] array, byte[] buffer) where T : struct
    {
      var len = Math.Min(array.GetLength(0) * array.GetLength(1) * System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)), buffer.Length);
      Buffer.BlockCopy(buffer, 0, array, 0, len);
    }
    

    【讨论】:

      【解决方案2】:

      如果您不害怕使用不安全的代码,那真的很简单:

              int[,] array = new int[2, 2];
      
              //Do whatever to fill the array
      
              byte[] buffer = new byte[array.GetLength(0) * array.GetLength(1) * sizeof(int)];
      
              fixed (void* pArray = &array[0,0])
              {
                  byte* pData = (byte*)pArray;
      
                  for (int buc = 0; buc < buffer.Length; buc++)
                      buffer[buc] = *(pData + buc);
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2014-06-21
        • 2019-01-23
        • 1970-01-01
        相关资源
        最近更新 更多