§ May 3, 2005

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)

Links to the other C# CRC implementations CRC16-CCITT, CRC16-CCITT Kermit, CRC16, and CRC8

I've consolidated all of these into a single library on GitHub here: NullFX.CRC.

I'm also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package
Posted 20 years, 8 months ago on May 3, 2005

Comments have now been turned off for this post

© 2003 - 2024 NullFX
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License