说明:CRC即循环冗余校验码(Cyclic Redundancy Check):是数据通信领域中最常用的一种查错校验码,其特征是信息字段和校验字段的长度可以任意选定。循环冗余检查(CRC)是一种数据传输检错功能,对数据进行多项式计算,并将得到的结果附在帧的后面,接收设备也执行类似的算法,以保证数据传输的正确性和完整性。
1. 推荐一个可以在线CRC计算的网站:
http://www.ip33.com/crc.html
测试数据:AB 01 20 75 D0 85 00 00 00 00 00 01
CRC16 = 4845
CRC32 = ED620F2C
2. CRC 、AES 计算软件
软件还未开发完成,后续完成再上次并附带下载链接,请先关注。
3. CRC 计算代码
public class CrcCheck
{public static byte CRC8(byte[] buffer){byte crc = 0;for (int j = 1; j <= buffer.Length; j++){crc ^= buffer[j];for (int i = 0; i < 8; i++){if ((crc & 0x01) != 0){crc >>= 1;crc ^= 0x8c;}else{crc >>= 1;}}}return crc;}/// <summary>/// 字节0是高八位,字节1是第八位/// </summary>/// <param name="buffer"></param>/// <returns></returns>public static byte[] CRC16(byte[] data){int crc = 0xffff;for (int i = 0; i < data.Length; i++){crc = crc ^ data[i];for (int j = 0; j < 8; j++){int temp = 0;temp = crc & 1;crc = crc >> 1;crc = crc & 0x7fff;if (temp == 1){crc = crc ^ 0xa001;}crc = crc & 0xffff;}}//CRC寄存器高低位互换byte[] crc16 = new byte[2];crc16[1] = (byte)((crc >> 8) & 0xff);crc16[0] = (byte)(crc & 0xff);return crc16;}public static UInt16 CRC16_U16(byte[] data){byte[] crc16 = CRC16(data);UInt16 crc16_u16 = 0;crc16_u16 = crc16[1];crc16_u16 = (ushort)((crc16_u16 << 8) | (UInt16)crc16[0]);return crc16_u16;}public class CRC32{private static uint[] crcTable;private const uint polynomial = 0xEDB88320;public static uint Calculate(byte[] bytes){if (crcTable == null){InitializeCrcTable();}uint crc = 0xFFFFFFFF;for (int i = 0; i < bytes.Length; i++){byte index = (byte)(((crc) & 0xFF) ^ bytes[i]);crc = (crc >> 8) ^ crcTable[index];}return ~crc;}public static byte[] Calculate_byte(byte[] bytes){uint crc32_u = Calculate(bytes);byte[] crc_byte = BitConverter.GetBytes(crc32_u);return crc_byte;}private static void InitializeCrcTable(){crcTable = new uint[256];for (uint i = 0; i < 256; i++){uint crc = i;for (int j = 0; j < 8; j++){crc = (crc & 1) != 0 ? (crc >> 1) ^ polynomial : crc >> 1;}crcTable[i] = crc;}}}}