关闭

CRC16校验

174人阅读 评论(0) 收藏 举报

测试使用modbus通讯协议的电力表时 用到CRC16校验

/// <summary>
        /// CRC16校验
        /// </summary>
        /// <param name="RecData"></param>
        /// <returns></returns>
        public  byte[] DataValidation(byte[] data)
        {
            byte CRC16Hi;
            byte CRC16Lo;
            byte CL;
            byte CH;
            byte SaveHi;
            byte SaveLo;
            int i;
            int flag;
            CRC16Hi = 0xff;
            CRC16Lo = 0xff;
            CL = 0x01;
            CH = 0xA0;
            byte[] result = new byte[2];
            try
            {
                for (i = 0; i < data.Length; i++)
                {
                    CRC16Lo = (byte)((int)CRC16Lo ^ (int)data[i]);

                    for (flag = 0; flag < 8; flag++)
                    {
                        SaveHi = CRC16Hi;
                        SaveLo = CRC16Lo;
                        CRC16Hi = (byte)((int)CRC16Hi >> 1);
                        CRC16Lo = (byte)((int)CRC16Lo >> 1);
                        if ((SaveHi & 0x01) == 0x01)
                        {
                            CRC16Lo = (byte)((int)(CRC16Lo) | (int)0x80);
                        }
                        if ((SaveLo & 0x01) == 0x01)
                        {
                            CRC16Hi = (byte)((int)CRC16Hi ^ (int)CH);
                            CRC16Lo = (byte)((int)CRC16Lo ^ (int)CL);
                        }
                    }
                }
            }
            catch
            {
                result[0] = 0x7F;
                result[1] = 0x7F;
            }
            result[0] = CRC16Lo;
            result[1] = CRC16Hi;
            return result;
        }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:405次
    • 积分:15
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档
    阅读排行
    评论排行