使用 C# 实现 Bin 类,快速方便地管理 byte[] 类型

提示

这是 2007 年我初学编程时写的文章,现在看来很多问题,但求搏君一笑。

使用 C# 实现 Bin 类,快速方便地管理 byte[] 类型一直是我的心愿。因为在 C C++ C# VB 等语言中,byte[] 类型是常用的,但却没有太多方便的命令去处理它。因此我编写了 Bin 类。这个类实现了方便的管理,封装了大部分 Byte[] 操作,如添加、删除、查找等。在编写中注重速度、效率和方便性,支持索引器[index]直接引用,操作符重载等。

同时这也是我写的“ToEasy”C#简单化代码的一部分,namespace 就是 ToEasy 了!

下面就是我写的代码:

 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
/* Bin 操作类
 * 版本:1.0
 * --
 * 欢迎访问:http://ceeji.net (博客)
 *
 */
namespace ToEasy
{
    /// <summary>
    /// 可以容纳字节数组数据。简化了对数据的操作。
    /// </summary>
    public class Bin
    {
        //字段
        byte[] data = new byte[0];
 
        //属性
        public Byte[] ByteArray
        {
            get
            {
                return this.data;
            }
        }
        public int Length
        {
            get
            {
                return this.data.Length;
            }
        }
 
        //隐式转换
        public static implicit operator Bin(byte[] from)
        {
            return new Bin(from);
        }
        public static implicit operator byte[] (Bin from)
        {
            return (byte[])from.data.Clone();
        }
        //运算
        public static bool operator ==(Bin bin, byte[] o)
        {
            return bin.ByteArray == o;
        }
        public static bool operator !=(Bin bin, byte[] o)
        {
            return bin.ByteArray != o;
        }
        public static bool operator ==(byte[] o, Bin bin)
        {
            return bin == o;
        }
        public static bool operator !=(byte[] o, Bin bin)
        {
            return bin != o;
        }
        public static Bin operator +(Bin bin1, Bin bin2)
        {
            return bin1.GetAppend((byte[])bin2);
        }
        //索引器
        public byte this[int index]
        {
            get
            {
                return this.GetByte(index);
            }
            set
            {
                this.data[index] = value;
            }
        }
        //构造
        public Bin()
        {
        }
        public Bin(byte[] from)
        {
            this.FromByteArray(from);
        }
        public Bin(int length)
        {
            this.data = new byte[length];
        }
        //方法
        public void Clear()
        {
            data = new byte[0];
        }
        public void FromByteArray(byte[] byteArray)
        {
            data = (byte[])byteArray.Clone();
        }
        public void FromFile(string fileName)
        {
            this.FromByteArray(File.ReadAllBytes(fileName));
        }
        /// <summary>
        /// 向现在的字节集的末尾添加数据。
        /// </summary>
        /// <param name="append">字节集数据,可以为 byte[] 或 Bin.</param>
        public void Append(byte[] append)
        {
            byte[] nbyte = new byte[this.Length + append.Length];
            this.data.CopyTo(nbyte, 0);
            append.CopyTo(nbyte, this.Length);
            this.FromByteArray(nbyte);
        }
        public Bin GetAppend(byte[] append)
        {
            Bin bin = new Bin();
            byte[] nbyte = new byte[this.Length + append.Length];
            this.data.CopyTo(nbyte, 0);
            append.CopyTo(nbyte, this.Length);
            bin.FromByteArray(nbyte);
            return bin;
        }
        public byte GetByte(int index)
        {
            return data[index];
        }
        public byte[] GetLeft(int length)
        {
            byte[] ret = new byte[length];
            Array.Copy(data, 0, ret, 0, length);
            return ret;
        }
        public byte[] GetData(int startIndex, int length)
        {
            byte[] ret = new byte[length];
            Array.Copy(data, startIndex, ret, 0, length);
            return ret;
        }
        public byte[] GetRight(int length)
        {
            byte[] ret = new byte[length];
            Array.Copy(data, this.Length - length - 1, ret, 0, length);
            return ret;
        }
        /// <summary>
        /// 返回当前对象的字符串形式,例如 { 57, 46 }
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (data.Length == 0)
            {
                return "{ }";
            }
            StringBuilder str = new StringBuilder("{ ");
            foreach (byte each in data)
            {
                str.Append(each.ToString());
                str.Append(", ");
            }
            str.Remove(str.Length - 2, 2);
            str.Append(" }");
            return str.ToString();
        }
        /// <summary>
        /// 移除某项。这会很浪费时间,尽量不要这样做。
        /// </summary>
        /// <param name="startindex"></param>
        /// <param name="length"></param>
        public void Remove(int startindex, int length)
        {
            if (length < 1)
            {
                return;
            }
            byte[] ndata = new byte[this.Length - length];
            int j = 0;
            for (int i = 0; i <= this.Length - 1; i++)
            {
                if ((i >= startindex & i < = startindex + length) == false)
                {
                    ndata[j] = this[i];
                    j++;
                }
            }
            this.data = (byte[])ndata.Clone();
        }
        /// <summary>
        /// 在当前字节集中查找子字节集。如果找到则返回索引位置,否则返回 -1。
        /// 
        /// <param name="findbin">要找的数据</param>
        /// <returns>索引位置</returns>
        public int Find(Bin findbin)
        {
            byte[] b = findbin.ByteArray ;
            int l = findbin.Length;
            int z = this.Length - l + 1;
            for (int i = 0; i < = z; i++)
            {
                if (findbin.GetData(i, l) == b)
                {
                    return i;
                }
            }
            return -1;
        }
        /// <summary>
        /// 在当前字节集中从后向前查找子字节集。如果找到则返回索引位置,否则返回 -1。
        /// 
        /// <param name="findbin">要找的数据</param>
        /// <returns>索引位置</returns>
        public int FindLast(Bin findbin)
        {
            byte[] b = findbin.ByteArray;
            int l = findbin.Length;
            int z = this.Length - l + 1;
            for (int i = z; i == 0; i--)
            {
                if (findbin.GetData(i, l) == b)
                {
                    return i;
                }
            }
            return -1;
        }
        /// <summary>
        /// 执行替换。
        /// </summary>
        /// <param name="startindex">开始位置索引</param>
        /// <param name="length">替换长度</param>
        /// <param name="bin">替换成的数据</param>
        public bool Replace(int startindex, int length, Bin bin)
        {
            if (startindex > this.Length - 1)//开始位置超标
            {
                return false;
            }
            if (startindex + length > this.Length)//结束位置超标
            {
                return false;
            }
            if (bin.Length < length)//提供数据不足
            {
                return false;
            }
            byte[] b = bin.ByteArray;
            int j = 0;
            for (int i = startindex; i <= startindex + length - 1; i++)
            {
                this.data[i] = b[j];
                j++;
            }
            return true;
        }
        /// <summary>
        /// 将当前字节集写到指定的文件中。如果文件已存在,该文件将被覆盖。
        /// 
        /// <param name="filename">文件名</param>
        /// <param name="append">是否追加</param>
        public void WriteToFile(string filename, bool append)
        {
            if (append == false)
            {
                File.WriteAllBytes(filename, this.ByteArray);
            }
            else
            {
                FileStream stream = new FileStream (filename,FileMode.Append );
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(this.ByteArray);
                writer.Close();
                stream.Close();
            }
        }
        /// <summary>
        /// 将当前字节集写入文件基础流。
        /// </summary>
        /// <param name="stream">文件基础流</param>
        public void WriteToFileStream(FileStream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);
            writer.Write(this.ByteArray);
            writer.Close();
        }
    }
}

本文版权遵循 CC BY-NC-SA 4.0发布,转载需附带本文链接。

当前页阅读量为: