c# CRC-16 / MODBUS 校验计算方法 及 异或校验算法

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

只要是代码,如下:

        /// <summary>
        /// 低字节在前
        /// </summary>
        /// <param name="pDataBytes"></param>
        /// <returns></returns>
        static byte[] CRC16LH(byte[] pDataBytes)
        {
            ushort crc = 0xffff;
            ushort polynom = 0xA001;

            for (int i = 0; i < pDataBytes.Length; i++)
            {
                crc ^= pDataBytes[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 0x01)
                    {
                        crc >>= 1;
                        crc ^= polynom;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }

           byte[] result = BitConverter.GetBytes(crc);
           return result;
        }

        /// <summary>
        /// 高字节在前
        /// </summary>
        /// <param name="pDataBytes"></param>
        /// <returns></returns>
        static byte[] CRC16HL(byte[] pDataBytes)
        {
            ushort crc = 0xffff;
            ushort polynom = 0xA001;

            for (int i = 0; i < pDataBytes.Length; i++)
            {
                crc ^= pDataBytes[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 0x01)
                    {
                        crc >>= 1;
                        crc ^= polynom;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }

            byte[] result = BitConverter.GetBytes(crc).Reverse().ToArray() ;
            return result;
        }

还有两个供大家验证的byte数组,如下:

 List<byte> llsst = new List<byte>() {0x79,0x79,0x01,0x01,0x00,0x1C,0x01,0x90,0x00,0x01,0x28,0xC3,0xC1,0x00,0xE9,0x9E,0x00,0x00,0x00,0x00,0x52,0x85,0x00,0x01,0x11,0x8E,0x15,0x02,0xD0,0x41,0x3E,0x02,0x0B,0x00};
            var CrcLs3t22 = CRC16LH(llsst.ToArray());
            var CrcLs2t25 = CRC16HL(llsst.ToArray());

低字节在前的结果为:83 9A

高字节在前的结果为:9A 83

 

异或校验算法:

        public static byte XOR_Check(List<byte> pbuf)
        {
            int res = 0;
            int len = pbuf.Count;
            for (int i = 0; i < len; i++)
            {
                res ^= pbuf[i];
            }
            return BitConverter.GetBytes(res)[0];
        }

@天才卧龙的博客

posted @ 2020-11-10 16:24  天才卧龙  阅读(2956)  评论(0编辑  收藏  举报