【C#】CRC16校验

/// <summary>
/// CRC16校验
/// </summary>
/// <param name="buffer">数组</param>
/// <param name="buflen">数组字节长度</param>
/// <param name="sidx">帧开头</param>
/// <param name="endidx">帧结尾</param>
/// <returns></returns>
public UInt16 CRC16(byte[] buffer, int buflen, int sidx, int endidx)
{
  ushort crc = 0;
  try
  {
      if (buffer == null || buffer.Length == 0) return 0;
      if (endidx < sidx)
          endidx += buflen;
      for (int i = sidx; i < endidx; i++)
      {
          if (i < buflen)
              crc ^= buffer[i];
          else
              crc ^= buffer[i % buflen];
          for (int j = 0; j < 8; j++)
          {
              if ((crc & 1) > 0)
                  crc = (ushort)((crc >> 1) ^ 0xA001);
              else
                  crc = (ushort)(crc >> 1);
          }
      }
  }
  catch (Exception ex)
  {
      DebugOutput.ProcessMessage(string.Format("[ERROR] ex{0}", ex.Message));
  }
  return crc;
}
posted @ 2024-03-19 11:28  qiutian-hao  阅读(254)  评论(0)    收藏  举报