C#学习笔记:Byte[]的合并与分割

using System;
using System.Collections.Generic;
using System.Text;

namespace BytesEncodeDecode
{
    class Program
    {
        static void Main(string[] args)
        {
            //原始字符串
            string[] test = new string[5];
            test[0] = "AAAAAAAAA";
            test[1] = "BBBBBBBBB";
            test[2] = "CCCCCCCCC";
            test[3] = "DDDDDDDDD";
            test[4] = "EEEEEEEEE";

            //输出测试
            Console.WriteLine("Origin:");
            foreach (var item in test)
            {
                Console.WriteLine(item);
            }

            //编码
            byte[] result1 = Encode(Encoding.UTF8.GetBytes(test[0]), Encoding.UTF8.GetBytes(test[1]), Encoding.UTF8.GetBytes(test[2]), Encoding.UTF8.GetBytes(test[3]), Encoding.UTF8.GetBytes(test[4]));

            //输出测试
            Console.Write("\n\n");
            Console.WriteLine("Encode:");
            foreach (var item in result1)
            {
                Console.Write(item);
                Console.Write(",");
            }

            //解码
            byte[][] result2 = Decode(result1);

            //输出测试
            Console.Write("\n\n");
            Console.WriteLine("Decode:");
            for (int i = 0; i < result2.Length; i++)
            {
                string output = Encoding.UTF8.GetString(result2[i]);
                Console.WriteLine(output);
            }


            Console.ReadKey();
        }

        //编码,将多个byte[]合并、添加分隔符
        public static byte[] Encode(params byte[][] args)
        {
            byte splitChar = 124;//124:'|'
            int count = args.Length;

            List<byte> byteList = new List<byte>();
            for (int i = 0; i < count; i++)
            {
                byteList.AddRange(args[i]);
                byteList.Add(splitChar);
            }
            return byteList.ToArray();
        }

        //解码,从一个byte[]里根据分隔符拆分
        public static byte[][] Decode(byte[] args)
        {
            byte splitChar = 124;//124:'|'
            List<byte>[] byteList = new List<byte>[10];
            byteList[0] = new List<byte>();

            //byteList计数,从第0个byteList开始
            int count = 0;

            foreach (byte item in args)
            {
                if (item != splitChar)
                {
                    byteList[count].Add(item);
                }
                else
                {
                    //遇到分隔符,创建一个新的byteList
                    count++;
                    byteList[count] = new List<byte>();
                }
            }

            //将List<Byte>数组转换成byte[][]二维数组
            byte[][] result = new byte[count][];
            for (int i = 0; i < count; i++)
            {
                result[i] = byteList[i].ToArray();
            }

            return result;
        }
    }
}

测试:

《C#学习笔记:Byte[]的合并与分割》

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注