【问题标题】:How to convert an int[,] to byte[] in C#如何在 C# 中将 int[,] 转换为 byte[]
【发布时间】:2010-07-23 21:23:27
【问题描述】:

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

编辑:

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

byte[] FuncName (int[,] Input)

【问题讨论】:

  • 这毫无意义,我的头很痛。你需要指定更多的东西——太多了,我什至无法全部列出!让我们从“您要解决的问题到底是什么?”
  • 添加了更多细节。
  • [,]int[]byte 应该是什么意思?这在 C# 中不存在,您的意思可能是 int[,]byte[]...
  • 不幸的是,这不是细节。 如何 您需要对其进行编码吗?你有预期的输入/输出吗?还是您只是在寻找想法?
  • 也许这是一个二进制序列化问题?

标签: c# multidimensional-array bytearray


【解决方案1】:

由于您的问题几乎没有细节,我只能猜测您要做什么...假设您想将二维整数数组“展平”为一维字节数组,您可以做一些事情像这样:

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

注意对 Cast 的调用:这是因为多维数组实现了 IEnumerable 而不是 IEnumerable&lt;T&gt;

【讨论】:

    【解决方案2】:

    您似乎写错了类型,但您可能正在寻找以下内容:

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

    【讨论】:

    • 我猜你猜“最有可能是他的目标”。
    • @mquander 是的,但我的似乎符合他的需要。
    【解决方案3】:

    这是假设您正在尝试序列化的一个实现;不过,不知道这是否是您想要的;它以尺寸为前缀,然后每个单元格使用基本编码:

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

    【讨论】:

      【解决方案4】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-02-03
        • 2011-08-19
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 2017-03-18
        • 2012-08-01
        • 1970-01-01
        相关资源
        最近更新 更多