C#串口通信中的奇偶性校验、CRC校验函数

一般来说,通信协议中的通用数据格式是 包头+指令码+数据长度+有效数据+校验码+包尾。

其中,校验方式有多种,最流行的是CRC校验方式,其次是简单的奇偶性校验。校验码是根据上述方式来计算【除了包头包尾和校验码的其他字节】来得到的,也即是下面函数的入参。

废话不多说,直接上方法(感兴趣的话可以百度搜一下计算原理)

CRC校验生成的校验码是2个字节,奇偶性校验生成的是1个字节。

        /// <summary>
        /// CRC校验
        /// </summary>
        /// <param name="data">校验数据</param>
        /// <returns>高低8位</returns>
        public static byte[] CRCCalc(byte[] bytedata)
        {
            byte[] res = new byte[2];
            byte[] crcbuf = bytedata.ToArray();
            //计算并填写CRC校验码
            int crc = 0xffff;
            int len = crcbuf.Length;
            for (int n = 0; n < len; n++)
            {
                byte i;
                crc = crc ^ crcbuf[n];
                for (i = 0; i < 8; i++)
                {
                    int TT;
                    TT = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (TT == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }

            }
            res[1] = (byte)((crc >> 8) & 0xff);
            res[0] = (byte)((crc & 0xff));
            return res;

        }

奇偶性校验方式大家在网上很难搜到,我也是搜了挺久最后才发现很简单,其实就是把所有字节加起来得到的数,也叫奇偶和校验(其实还有所谓的奇校验和偶校验,这两种不常用反而混淆视听,在此不做赘述)。下面列出两种方式,一种是C常用,一种是C#累加

 byte GetParity(byte[] SendBuf)
        {
            byte Parity = 0; //计算奇偶校验和
            for (int i = 0; i < SendBuf.Length; i++)
            {

                Parity = (byte)(Parity ^ SendBuf[i]);
            }

            return Parity;
        }
  byte GetParity2(byte[] SendBuf)
        {
            byte Parity = 0; //计算奇偶校验和
            for (int i = 0; i < SendBuf.Length; i++)
            {

                Parity = (byte)(Parity +SendBuf[i]);
            }

            return Parity;
        }

如果对大家有用,别忘了点赞哟~~~感谢大家的鼓励!

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值