合并byte数组

假如有这么几个byte[],想要把它们合成一个byte[]。

1             byte[] bytes1 = { 1, 2, 3, 4, 5 };
2             byte[] bytes2 = { 6, 7, 8, 9 };
3             byte[] bytes3 = { 10, 11, 12, 13, 14, 15 };

一般我们会这么写:

1             byte[] allBytes1 = new byte[bytes1.Length + bytes2.Length + bytes3.Length];
2             bytes1.CopyTo(allBytes1, 0);
3             bytes2.CopyTo(allBytes1, bytes1.Length);
4             bytes3.CopyTo(allBytes1, bytes1.Length + bytes2.Length);
5             foreach (byte item in allBytes1)
6             {
7                 Console.WriteLine(item);
8             }

不过,这样感觉好麻烦,如果要合并的byte[]太多,CopyTo()会调用你想吐,第二个参数的值也会让你+Length加到你郁闷至死,怎么办?写个方法吧。调用这一个ConcatBytes方法就行了,参数是动态的,可以放无数个。

            // 合并byte[]
            byte[] allBytes2 = ConcatBytes(bytes1, bytes2, bytes3);
            foreach (byte item in allBytes2)
            {
                Console.WriteLine(item);
            }

        /// <summary>
        /// 合并byte数组
        /// </summary>
        /// <param name="sourceBytesArray">要合并的数组集合</param>
        /// <returns>合并后的byte数组</returns>
        private byte[] ConcatBytes(params byte[][] sourceBytesArray)
        {
            int allLength = sourceBytesArray.Sum(o => o.Length);
            byte[] resultBytes = new byte[allLength];
            for (int i = 0; i < sourceBytesArray.Length; i++)
            {
                int copyToIndex = GetCopyToIndex(sourceBytesArray, i);
                sourceBytesArray[i].CopyTo(resultBytes, copyToIndex);
            }
            return resultBytes;
        }

        /// <summary>
        /// 获取复制开始处的索引
        /// </summary>
        /// <param name="sourceBytesArray">byte[]的所在数组</param>
        /// <param name="index">byte[]的所在数组的索引</param>
        /// <returns>复制开始处的索引</returns>
        private int GetCopyToIndex(byte[][] sourceBytesArray, int index)
        {
            if (index == 0)
            {
                return 0;
            }
            return sourceBytesArray[index - 1].Length + GetCopyToIndex(sourceBytesArray, index - 1);
        }

其实,用Framework提供的方法感觉更简单

1             List<byte> sendByteList = new List<byte>();
2             sendByteList.AddRange(bytes1);
3             sendByteList.AddRange(bytes2);
4             sendByteList.AddRange(bytes3);
5             byte[] allBytes3 = sendByteList.ToArray();
6             foreach (byte item in allBytes3)
7             {
8                 Console.WriteLine(item);
9             }

  

  

原文地址:https://www.cnblogs.com/yuwuji/p/8081897.html