admin 发表于 2022-5-8 09:56:22

crc16代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace crc16
{
    class Program
    {
      static void Main(string[] args)
      {
            ushort crcresult = 0;
            byte[] puchmsg = { 0x01,0x01,0x00,0x00, 0x00, 0x09 };
            crcresult = CRC16_MODBUS(puchmsg,6);//MODBUS协议CRC16校验结果
            string str_crc = string.Format("0x{0:X2}", crcresult);
            Console.WriteLine("MODBUS输出结果:低8位:{0},高8位:{1}", Convert.ToString(crcresult & 0xff, 16), Convert.ToString((crcresult & 0xff00) >> 8, 16));
            Console.WriteLine("MODBUS输出结果:{0}", str_crc);
            
            Console.Read();                                                                                                                                    
      }


      static ushort CRC16_MODBUS(byte[] puchMsg, int usDataLen)
      {
          ushortwCRCin = 0xFFFF;
          ushort wCPoly = 0x8005;
          byte wChar = 0;
          byte a = 0;
          for (int j = 0; j < usDataLen;j++ )
          {
            wChar = puchMsg;
            wChar = InvertUint8(wChar);
            wCRCin ^= (ushort)(wChar << 8);
            for (int i = 0; i < 8; i++)
            {
                  if ((wCRCin & 0x8000)==0x8000)
                      wCRCin = (ushort)((wCRCin << 1) ^ wCPoly);
                  else
                      wCRCin = (ushort)(wCRCin << 1);
            }
          }
          wCRCin = InvertUint16(wCRCin);
          return (wCRCin);
      }
      static byte InvertUint8(byte inputdata)
      {
            byte a0 = 0;
            for (int i = 0; i < 8; i++)
            {
                if ((inputdata & ((byte)Math.Pow(2, i))) == ((byte)Math.Pow(2, i)))
                {
                  a0 |= (byte)Math.Pow(2, 7 - i);
                }
                else
                { a0 |= 0x00; }
            }
            return a0;
      }
      static ushort InvertUint16(ushort inputdata)
      {
            ushort a0 = 0;
            for (int i = 0; i < 16; i++)
            {
                if ((inputdata & ((ushort)Math.Pow(2, i))) == ((ushort)Math.Pow(2, i)))
                {
                  a0 |= (ushort)Math.Pow(2, 15 - i);
                }
                else
                { a0 |= 0x00; }
            }
            return a0;
      }
    }
}
页: [1]
查看完整版本: crc16代码实现