using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MECF.Framework.RT.Core.IoProviders.Siemens.Transfer { /// /// 按照字节错位的数据转换类 /// public class ReverseWordTransform : ByteTransformBase { #region Constructor /// /// 实例化一个默认的对象 /// public ReverseWordTransform( ) { this.DataFormat = DataFormat.ABCD; } /// /// 使用指定的数据解析来实例化对象 /// /// 数据规则 public ReverseWordTransform( DataFormat dataFormat ) : base( dataFormat ) { } #endregion #region Private Method /// /// 按照字节错位的方法 /// /// 实际的字节数据 /// 起始字节位置 /// 数据长度 /// 处理过的数据信息 private byte[] ReverseBytesByWord( byte[] buffer, int index, int length ) { if (buffer == null) return null; // copy data byte[] tmp = new byte[length]; for (int i = 0; i < length; i++) { tmp[i] = buffer[index + i]; } // change for (int i = 0; i < length / 2; i++) { byte b = tmp[i * 2 + 0]; tmp[i * 2 + 0] = tmp[i * 2 + 1]; tmp[i * 2 + 1] = b; } return tmp; } private byte[] ReverseBytesByWord( byte[] buffer ) { return ReverseBytesByWord( buffer, 0, buffer.Length ); } #endregion #region Public Properties /// /// 字符串数据是否按照字来反转 /// public bool IsStringReverse { get; set; } #endregion #region Get Value From Bytes /// /// 从缓存中提取short结果 /// /// 缓存数据 /// 索引位置 /// short对象 public override short TransInt16( byte[] buffer, int index ) { return base.TransInt16( ReverseBytesByWord( buffer, index, 2 ), 0 ); } /// /// 从缓存中提取ushort结果 /// /// 缓存数据 /// 索引位置 /// ushort对象 public override ushort TransUInt16( byte[] buffer, int index ) { return base.TransUInt16( ReverseBytesByWord( buffer, index, 2 ), 0 ); } /// /// 从缓存中提取string结果,使用指定的编码 /// /// 缓存对象 /// 索引位置 /// byte数组长度 /// 字符串的编码 /// string对象 public override string TransString( byte[] buffer, int index, int length, Encoding encoding ) { byte[] tmp = TransByte( buffer, index, length ); if(IsStringReverse) { return encoding.GetString( ReverseBytesByWord( tmp ) ); } else { return encoding.GetString( tmp ); } } #endregion #region Get Bytes From Value /// /// short数组变量转化缓存数据 /// /// 等待转化的数组 /// buffer数据 public override byte[] TransByte( short[] values ) { byte[] buffer = base.TransByte( values ); return ReverseBytesByWord( buffer ); } /// /// ushort数组变量转化缓存数据 /// /// 等待转化的数组 /// buffer数据 public override byte[] TransByte( ushort[] values ) { byte[] buffer = base.TransByte( values ); return ReverseBytesByWord( buffer ); } /// /// 使用指定的编码字符串转化缓存数据 /// /// 等待转化的数据 /// 字符串的编码方式 /// buffer数据 public override byte[] TransByte( string value, Encoding encoding ) { if (value == null) return null; byte[] buffer = encoding.GetBytes( value ); buffer = SoftBasic.ArrayExpandToLengthEven( buffer ); if (IsStringReverse) { return ReverseBytesByWord( buffer ); } else { return buffer; } } #endregion } }