CRC32/CRC16算法C#中的实现
CRC32算法
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 6 namespace GetCRC32 7 { 8 class CRC32Cls 9 { 10 protected ulong[] Crc32Table; 11 //生成CRC32码表 12 public void GetCRC32Table() 13 { 14 ulong Crc; 15 Crc32Table = new ulong[256]; 16 int i,j; 17 for(i = 0;i < 256; i++) 18 { 19 Crc = (ulong)i; 20 for (j = 8; j > 0; j--) 21 { 22 if ((Crc & 1) == 1) 23 Crc = (Crc >> 1) ^ 0xEDB88320; 24 else 25 Crc >>= 1; 26 } 27 Crc32Table[i] = Crc; 28 } 29 } 30 31 //获取字符串的CRC32校验值 32 public ulong GetCRC32Str(string sInputString) 33 { 34 //生成码表 35 GetCRC32Table(); 36 byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(sInputString); 37 ulong value = 0xffffffff; 38 int len = buffer.Length; 39 for (int i = 0; i < len; i++) 40 { 41 value = (value >> 8) ^ Crc32Table[(value & 0xFF)^ buffer[i]]; 42 } 43 return value ^ 0xffffffff; 44 } 45 } 46 }
CRC16算法
1 public static byte[] CRC16(string sInputString) 2 { 3 byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(sInputString); 4 int len = data.Length; 5 if (len > 0) 6 { 7 ushort crc = 0xFFFF; 8 9 for (int i = 0; i < len; i++) 10 { 11 crc = (ushort)(crc ^ (data[i])); 12 for (int j = 0; j < 8; j++) 13 { 14 crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1); 15 } 16 } 17 byte hi = (byte)((crc & 0xFF00) >> 8); //高位置 18 byte lo = (byte)(crc & 0x00FF); //低位置 19 20 return new byte[] { hi, lo }; 21 } 22 return new byte[] { 0, 0 }; 23 } 24 25 // ASCII码转为字符串 26 public static string ByteToString(byte[] arr, bool isReverse) 27 { 28 try 29 { 30 byte hi = arr[0], lo = arr[1]; 31 return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0'); 32 } 33 catch (Exception ex) { throw (ex); } 34 }