Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Crc32Calculator.cs - github.com/ClusterM/nes-containers.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d1bd837efd16b7462d356b6bcd6751239e0ab55a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
namespace com.clusterrr.Famicom.Containers
{
    public static class Crc32Calculator
    {
        static uint[] table = new uint[256];

        static Crc32Calculator()
        {
            // Calculate table
            uint poly = 0xedb88320;
            uint temp;
            for (uint i = 0; i < table.Length; ++i)
            {
                temp = i;
                for (int j = 8; j > 0; --j)
                {
                    if ((temp & 1) == 1)
                    {
                        temp = (uint)((temp >> 1) ^ poly);
                    }
                    else
                    {
                        temp >>= 1;
                    }
                }
                table[i] = temp;
            }
        }

        /// <summary>
        /// Calculate CRC32 checksum
        /// </summary>
        /// <param name="data">Input data</param>
        /// <param name="offset">Data offset</param>
        /// <param name="length">Length</param>
        /// <returns></returns>
        public static uint CalculateCRC32(byte[] data, int offset, int length)
        {
            // Calculate CRC32
            uint crc = 0xffffffff;
            for (int i = offset; length > 0; i++, length--)
            {
                byte index = (byte)(((crc) & 0xff) ^ data[i]);
                crc = (crc >> 8) ^ table[index];
            }
            return ~crc;
        }

        /// <summary>
        /// Calculate CRC32 checksum
        /// </summary>
        /// <param name="data">Input date</param>
        /// <returns></returns>
        public static uint CalculateCRC32(byte[] data)
            => CalculateCRC32(data, 0, data.Length);
    }
}