using System; using System.Collections.Generic; namespace GPSBusiness.Helper { /// /// 字节流的操作类 /// public class ByteBuilder { private byte[] _buffer = null; private int _currentLength = 0; public int Length { get { return _currentLength; } } public ByteBuilder() { _buffer = new byte[0]; } public ByteBuilder(int length) { _buffer = new byte[length]; } public ByteBuilder(byte[] buffer) { _buffer = buffer; } /// /// 更新字节流数组长度 /// private void AppendBufferLength(int length) { _currentLength += length; if (_currentLength > this._buffer.Length) { byte[] newbyte = new byte[_currentLength]; this._buffer.CopyTo(newbyte, 0); this._buffer = newbyte; } } public void Append(byte value) { AppendBufferLength(1); this._buffer.SetValue(value, this._currentLength - 1); } public void Append(byte[] buffer) { AppendBufferLength(buffer.Length); Array.Copy(buffer, 0, this._buffer, _currentLength - buffer.Length, buffer.Length); } public void Append(byte[] buffer, int index, int length) { byte[] newbyte = new byte[length]; Array.Copy(buffer, index, newbyte, 0, Math.Min(length, buffer.Length)); this.Append(newbyte); } public void Insert(int index, byte[] buffer) { _currentLength += buffer.Length; byte[] newbyte = null; if (_currentLength > this._buffer.Length) { newbyte = new byte[_currentLength]; } else { newbyte = new byte[this._buffer.Length]; } Array.Copy(this._buffer, 0, newbyte, 0, index); Array.Copy(buffer, index, newbyte, index, buffer.Length); Array.Copy(this._buffer, index, newbyte, index + buffer.Length, _currentLength - index - buffer.Length); this._buffer = newbyte; } public void Insert(int index, byte value) { this.Insert(index, new byte[1] { value }); } public byte GetByte(int index) { return (byte)BitConverter.ToChar(_buffer, index); } public byte[] GetBytes() { return _buffer; } public byte[] GetBytes(int index, int length) { byte[] buffer = new byte[length]; Array.Copy(_buffer, index, buffer, 0, length); return buffer; } public void Clear() { this._buffer = new byte[0]; } public List Splite(byte value) { return Splite(value, 0, -1); } public List Splite(byte value, int start, int length) { List list = new List(); if (length == -1) { length = this._buffer.Length; } else { length = Math.Min(length, this._buffer.Length); } int index = start; for (int i = start; i < length; i++) { byte b = _buffer[i]; if (b == value) { int len = i - index; byte[] buffer = new byte[len]; if (len > 0) { Array.Copy(_buffer, index, buffer, 0, len); } list.Add(buffer); if (list.Count > 0) { index = i + 1; } else { index = i; } } } int len2 = _buffer.Length - index; if (len2 >= 0) { byte[] buffer = new byte[len2]; if (len2 > 0) { Array.Copy(_buffer, index, buffer, 0, len2); } list.Add(buffer); } return list; } } }