12.1 C#实现CRC32和CRC16

CRC32算法

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace GetCRC32
{
    class CRC32Cls
    {
        protected ulong[] Crc32Table;
        //生成CRC32码表
        public void GetCRC32Table() 
        {
            ulong Crc;
            Crc32Table = new ulong[256];
            int i,j;
            for(i = 0;i < 256; i++) 
            {
                Crc = (ulong)i;
                for (j = 8; j > 0; j--)
                {
                    if ((Crc & 1) == 1)
                        Crc = (Crc >> 1) ^ 0xEDB88320;
                    else
                        Crc >>= 1;
                }
                Crc32Table[i] = Crc;
            }
        }

        //获取字符串的CRC32校验值
        public ulong GetCRC32Str(string sInputString)
        {
            //生成码表
            GetCRC32Table();
            byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(sInputString);
            ulong value = 0xffffffff;
            int len = buffer.Length;
            for (int i = 0; i < len; i++)
            {
                value = (value >> 8) ^ Crc32Table[(value & 0xFF)^ buffer[i]];
            }
            return value ^ 0xffffffff; 
        }
    }
}

CRC16算法

public static byte[] CRC16(string sInputString)
         {
             byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(sInputString);
             int len = data.Length;
             if (len > 0)
             {
                 ushort crc = 0xFFFF;

                 for (int i = 0; i < len; i++)
                 {
                     crc = (ushort)(crc ^ (data[i]));
                     for (int j = 0; j < 8; j++)
                     {
                         crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
                     }
                 }
                 byte hi = (byte)((crc & 0xFF00) >> 8);  //高位置
                 byte lo = (byte)(crc & 0x00FF);         //低位置

                 return new byte[] { hi, lo };
             }
             return new byte[] { 0, 0 };
         }

// ASCII码转为字符串
         public static string ByteToString(byte[] arr, bool isReverse)
         {
             try
             {
                 byte hi = arr[0], lo = arr[1];
                 return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0');
             }
             catch (Exception ex) { throw (ex); }
         }

results matching ""

    No results matching ""