zoukankan      html  css  js  c++  java
  • CRC32算法C#中的实现

    代码如下:

     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 }

    调用代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace GetCRC32
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                CRC32Cls CRC = new CRC32Cls();
                textBox2.Text = String.Format("{0:X8}", CRC.GetCRC32Str(textBox1.Text));
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
    
            }
        }
    }
  • 相关阅读:
    11-14序列化模块之json、pickle、shelve
    11-13 模块_collections(不太重要)&time&random&os
    Python常用标准库之datetime、random、hashlib、itertools
    模块安装说明
    __name__=='__main__'作用
    10-29 继承-单继承
    10-12 面向对象初级
    栈内存 堆内存
    【初识MyBatis→简单的mybatis开发环境搭建】
    【Linux常用命令小手册】
  • 原文地址:https://www.cnblogs.com/Kconnie/p/3538194.html
Copyright © 2011-2022 走看看