CRC 32アルゴリズムC#での実装

8459 ワード

コードは次のとおりです.
 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)

        {



        }

    }

}