首页 > 编程知识 正文

crc校验码计算代码c语言,crc校验码计算例题

时间:2023-05-05 22:32:00 阅读:279403 作者:548

namespace CRC
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] date = { 0x01, 0x05, 0x00, 0x00, 0xFF, 0x00 };   //要计算CRC校验的数据
            byte[] crc = new byte[2];    //用来保存CRC效验码
            crc = GetCRC(date);         //得到data的CRC码
            foreach (var item in crc)   
            {
                Console.Write(item.ToString("X2") + "  ");    //打印出CRC码
            }
            Console.WriteLine();
            Console.ReadKey();
        }


        public static byte[] GetCRC(byte[] byteData)   //计算CRC校验的数据方法
        {
            byte[] CRC = new byte[2];

            UInt16 wCrc = 0xFFFF;
            for (int i = 0; i < byteData.Length; i++)
            {
                wCrc ^= Convert.ToUInt16(byteData[i]);
                for (int j = 0; j < 8; j++)
                {
                    if ((wCrc & 0x0001) == 1)
                    {
                        wCrc >>= 1;
                        wCrc ^= 0xA001;    //异或多项式
                    }
                    else
                    {
                        wCrc >>= 1;
                    }
                }
            }

            CRC[1] = (byte)((wCrc & 0xFF00) >> 8);    //高位在后
            CRC[0] = (byte)(wCrc & 0x00FF);               //低位在前
            return CRC;

        }
    }
}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。