我将如何字节交换 ByteArray?

How would I byteswap a ByteArray?

我正在寻找一种对整个 ByteArray 进行字节交换的方法。例如,如果我有以下命令(例如!我的文件大小超过 300 字节),如下所示:

80 37 12 40

并将其加载到 ByteArray 中。我如何将它换成这个:

37 80 40 12

在我的项目中,通常的长度是4个字节。所以我不难解决这个问题:

   public static ushort SwapBytes(ushort x)
   {
       return (ushort)((ushort)((x & 0xff) << 8) | ((x >> 8) & 0xff));
   }

                   byte[] rev = Assembler.Operations.ToByteArray(towrite);
                   byte[] half = new byte[2];
                   byte[] half2 = new byte[2];
                   ushort tt = BitConverter.ToUInt16(rev, 0);
                   tt = SwapBytes(tt);

                   half = BitConverter.GetBytes(tt);

                   Start.fs.Write(half, 0, 2);

所以,但是如果我有一个超过 400 字节大的二进制文件,我该怎么做呢?我不能只做 ushort 字节交换。我想字节交换整个字节数组,如上所示。

简单地循环交换相邻的字节。无需转换为带掩码的 ushort 和 fiddle。

    static void SwapByteArray(byte[] a)
    {
        // if array is odd we set limit to a.Length - 1.
        int limit = a.Length - (a.Length % 2);
        if (limit < 1) throw  new Exception("array too small to be swapped.");
        for (int i = 0; i < limit - 1; i = i + 2)
        {
            byte temp = a[i];
            a[i] = a[i + 1];
            a[i + 1] = temp;
        }
    }