[C#]CRC16

来源:互联网 发布:广州动易软件 编辑:程序博客网 时间:2024/05/17 20:29
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace CRCTest{    class Program    {        static void Main(string[] args)        {            byte[] buf = new byte[128];            for (int i = 0; i < buf.Length; ++i) buf[i] = Convert.ToByte(i + 1);            UInt16 crc16 = CRC16(0x0000, 0x1021, buf, 0, buf.Length);            Console.WriteLine("{0:X4}", crc16);            Console.ReadLine();        }        /// <summary>        /// CRC16校验        /// </summary>        /// <param name="Initial">寄存器初值</param>        /// <param name="Generator">生成多项式,X^16+X^12+X^5+1,其生成多项式为0x1021</param>        /// <param name="buf">校验数据</param>        /// <param name="start">数据起始位置</param>        /// <param name="length">数据长度</param>        /// <returns>CRC16校验结果</returns>        private static UInt16 CRC16(UInt16 Initial, UInt16 Generator, byte[] buf, int start, int length)        {            for (int i = start; i < start + length; ++i)            {                byte b = buf[i];                for (int j = 0; j < 8; ++j)                {                    int t0 = b & 0x80;                    int t1 = Initial & 0x8000;                    Initial <<= 1;                    b <<= 1;                    if (t0 != 0) Initial += 1;                    if (t1 != 0) Initial ^= Generator;                }            }            for (int i = 0; i < 16; ++i)            {                int t1 = Initial & 0x8000;                Initial <<= 1;                if (t1 != 0) Initial ^= Generator;            }            return Initial;        }    }}