合並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             }

 


  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM