关闭

CRC算法 +c#

标签: 算法cbuffertablebytestring
529人阅读 评论(0) 收藏 举报
分类:

/// <summary>
  /// CRC 效验
  /// 快速检测算法
  /// </summary>
  public class CRC32{

    protected uint[] crc32Table;

    /// <summary>
    /// 构造:初始化效验表
    /// </summary>
    public CRC32() {
      const uint ulPolynomial = 0xEDB88320;
      uint dwCrc;
      crc32Table = new uint[256];
      int i,j;
      for(i = 0; i < 256; i++) {
        dwCrc = (uint)i;
        for(j = 8; j > 0; j--) {
          if((dwCrc & 1)==1)
            dwCrc = (dwCrc >> 1) ^ ulPolynomial;
          else
            dwCrc >>= 1;
        }
        crc32Table[i] = dwCrc;
      }
    }

    /// <summary>
    /// 字节数组效验
    /// </summary>
    /// <param name="buffer">ref 字节数组</param>
    /// <returns></returns>
    public uint ByteCRC(ref byte[] buffer) {
      uint ulCRC = 0xffffffff;
      uint len;
      len = (uint)buffer.Length;
      for (uint buffptr=0; buffptr < len; buffptr++) {
             uint tabPtr = ulCRC & 0xFF;
        tabPtr = tabPtr ^ buffer[buffptr];
        ulCRC = ulCRC >> 8;
        ulCRC = ulCRC ^ crc32Table[tabPtr];
      }
      return (ulCRC ^ 0xffffffff);
    }


    /// <summary>
    /// 字符串效验
    /// </summary>
    /// <param name="sInputString">字符串</param>
    /// <returns></returns>
    public uint StringCRC(string sInputString){
      byte[] buffer = Encoding.Default.GetBytes(sInputString);
      return ByteCRC(ref buffer);
    }

    /// <summary>
    /// 文件效验
    /// </summary>
    /// <param name="sInputFilename">输入文件</param>
    /// <returns></returns>
    public uint FileCRC(string sInputFilename){
      FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open,  System.IO.FileAccess.Read);
      byte[] bInput = new byte[inFile.Length];
      inFile.Read(bInput,0,bInput.Length);
      inFile.Close();

      return ByteCRC(ref bInput);
    }

  } 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:68741次
    • 积分:1119
    • 等级:
    • 排名:千里之外
    • 原创:38篇
    • 转载:7篇
    • 译文:0篇
    • 评论:17条
    最新评论
    wpf文章