12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- namespace AmrControl.Common
- {
- public class CRCHelper
- {
- #region CRC16
- public static byte[] CRC16(byte[] data)
- {
- int len = data.Length;
- if (len > 0)
- {
- ushort crc = 0xFFFF;
- for (int i = 0; i < len; i++)
- {
- crc = (ushort)(crc ^ (data[i]));
- for (int j = 0; j < 8; j++)
- {
- crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
- }
- }
- byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
- byte lo = (byte)(crc & 0x00FF); //低位置
- return new byte[] { hi, lo };
- }
- return new byte[] { 0, 0 };
- }
- public static byte[] CRC16(byte[] data, int startIndex, int len)
- {
- if (len > 0 && data != null)
- {
- ushort crc = 0xFFFF;
- for (int i = startIndex; i < startIndex + len && i < data.Length; i++)
- {
- crc = (ushort)(crc ^ (data[i]));
- for (int j = 0; j < 8; j++)
- {
- crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
- }
- }
- byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
- byte lo = (byte)(crc & 0x00FF); //低位置
- return new byte[] { hi, lo };
- }
- return new byte[] { 0, 0 };
- }
- #endregion
- }
- }
|