A CRC32 Implementation In C#

The other day I was looking for a simple CRC32 library... 

I couldn't find one (that suited my needs) so I wrote a quick and dirty implementation. 

here it is:

namespace NullFX.Security {
    using System;
    public class Crc32 {
        uint[] table;

        public uint ComputeChecksum(byte[] bytes) {
            uint crc = 0xffffffff;
            for(int i = 0; i < bytes.Length; ++i) {
                byte index = (byte)(((crc) & 0xff) ^ bytes[i]);
                crc = (uint)((crc >> 8) ^ table[index]);
            }
            return ~crc;
        }

        public byte[] ComputeChecksumBytes(byte[] bytes) {
            return BitConverter.GetBytes(ComputeChecksum(bytes));
        }

        public Crc32() {
            uint poly = 0xedb88320;
            table = new uint[256];
            uint temp = 0;
            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;
            }
        }
    }
}

Its admittedly small, and hardly anyone uses CRC32 for security purposes (at least I hope not), but it is a decent checksum generator for small non-critical items.

I needed a 32 bit sized number generator--I was implementing my own object.GetHashCode() and wanted to get an int hashcode for my own objects--and this seemed like a decent way to do it.

If you need for this code to be CLS compliant, you can change the method signature's return type from uint to long and it will operate the same (the uint crc value will be implicitly converted from uint to long)

转自:http://www.sanity-free.com/12/crc32_implementation_in_csharp.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值