Is it possible to do CRC-32 calculation in splits?

后端 未结 4 549
粉色の甜心
粉色の甜心 2021-02-04 06:22

I use this trivial function to calculate the CRC checksum of a given file:

long i, j = 0;
int k = 0;
uint crc = 0xFFFFFFFF;
FileInfo file_info = new FileInfo(fil         


        
4条回答
  •  不思量自难忘°
    2021-02-04 07:01

    I know this is an old question but this is what I use for "chunking" CRC calculations in case this helps anyone:

    public static class Crc32Checksum
    {
        private static readonly uint[] Table = GenerateTable();
    
        /// 
        /// Calculates a CRC32 value for the data given.
        /// 
        /// Data contents
        /// Byte offset to start reading
        /// Number of bytes to read
        /// The computed CRC32 value.
        public static int Calculate(byte[] data, int offset, int count) 
            => Calculate(0, data, offset, count);
    
        /// 
        /// Calculates a new CRC32 value given additional data for the current CRC value.
        /// 
        /// The current CRC value to start with
        /// Additional data contents
        /// Byte offset to start reading
        /// Number of bytes to read
        /// The computed CRC32 value.
        public static int Calculate(int currentCrc, byte[] data, int offset, int count)
        {
            unchecked
            {
                uint crc = ~(uint)currentCrc;
    
                for (int i = offset, end = offset + count; i < end; i++)
                    crc = (crc >> 8) ^ Table[(crc ^ data[i]) & 0xFF];
    
                return (int)~crc;
            }
        }
    
        private static uint[] GenerateTable()
        {
            unchecked
            {
                var table = new uint[256];
    
                const uint poly = 0xEDB88320;
    
                for (uint i = 0; i < table.Length; i++)
                {
                    uint crc = i;
    
                    for (int j = 8; j > 0; j--)
                    {
                        if ((crc & 1) == 1)
                            crc = (crc >> 1) ^ poly;
                        else
                            crc >>= 1;
                    }
    
                    table[i] = crc;
                }
    
                return table;
            }
        }
    }
    

提交回复
热议问题