一种设备的CRC16校验算法

CRC16校验算法,在数据通信校验中是常用的校验处理算法,该算法是针对一款特殊的设备的校验值封装算法,算法本身是通用的,差异在校验和中的校验因子。

这个一般与设备厂家指定协议时独立写死的。

 /// <summary>
    /// Obid的数据封装CRC16校验
    /// </summary>
    internal static class ObidCRC16Service
    {
        /// <summary>
        /// C# CRC16校验算法 -输出是包含原有数据
        /// </summary>
        /// <param name="buffer">原始数据</param>
        /// <returns>返回原始数据+2Byte的校验码</returns>
        public static byte[] CRC16(byte[] buffer)
        {
            byte[] temdata = new byte[buffer.Length + 2];
            int xda, xdapoly;
            int i, j, xdabit;
            xda = 0xFFFF;
            xdapoly = 0x8408;
            for (i = 0; i < buffer.Length; i++)
            {
                xda ^= buffer[i];
                for (j = 0; j < 8; j++)
                {
                    xdabit = (int)(xda & 0x01);
                    xda >>= 1;
                    if (xdabit == 1)
                        xda ^= xdapoly;
                }
            }
            Array.Copy(buffer, 0, temdata, 0, buffer.Length);
            temdata[temdata.Length - 2] = (byte)(xda & 0xFF);
            temdata[temdata.Length - 1] = (byte)(xda >> 8);
            return temdata;
        }
        /// <summary>
        /// C# CRC16校验算法
        /// </summary>
        /// <param name="buffer">原始数据</param>
        /// <param name="bufferLen">原始数据长度</param>
        /// <returns>两位校验码</returns>
        public static byte[] CRC16(byte[] buffer, int bufferLen)
        {
            byte[] temdata = new byte[2];
            int xda, xdapoly;
            int i, j, xdabit;
            xda = 0xFFFF;
            xdapoly = 0x8408;
            for (i = 0; i < bufferLen; i++)
            {
                xda ^= buffer[i];
                for (j = 0; j < 8; j++)
                {
                    xdabit = (int)(xda & 0x01);
                    xda >>= 1;
                    if (xdabit == 1)
                        xda ^= xdapoly;
                }
            }
            temdata[0] = (byte)(xda & 0xFF);
            temdata[1] = (byte)(xda >> 8);
            return temdata;
        }
    }


 

你可能感兴趣的:(一种设备的CRC16校验算法)