§ February 4, 2010

A CRC8 implementation in C#

So I've tackled CRC32, CRC16, CRC16-CCITT (and now CRC16-CCITT Kermit) implementations, and found myself wanting a CRC8 class to create checksums for small data (1-2 bytes) sets. Not having ever used or seen CRC8 in use before, I did some reading, and as far as I can tell, I've implemented it correctly... It works anyway, so without further ado, here's my implementation:

public static class Crc8 {
    static byte[] table = new byte[256];
    // x8 + x7 + x6 + x4 + x2 + 1
    const byte poly = 0xd5;

    public static byte ComputeChecksum(params byte[] bytes ) {
        byte crc = 0;
        if ( bytes != null && bytes.Length > 0 ) {
            foreach ( byte b in bytes ) {
                crc = table[crc ^ b];
            }
        }
        return crc;
    } 

    static Crc8( ) {
        for ( int i = 0; i < 256; ++i ) {
            int temp = i;
            for ( int j = 0; j < 8; ++j ) {
                if ( ( temp & 0x80 ) != 0 ) {
                    temp = ( temp << 1 ) ^ poly;
                } else {
                    temp <<= 1;
                }
            }
            table[i] = (byte)temp;
        }
    }
}

This one differs slightly (API wise) from my previous ones, mainly because I was using it for checksum'ing smaller bits of data, so I made the ComputeChecksum method a params argument instead of a first class array type.

Here's a sample of how I was using it (and testing it):
byte crc = Crc8.ComputeChecksum( 1, 2, 3 );
byte check = Crc8.ComputeChecksum( 1, 2, 3, crc );
// here check should equal 0 to show that the checksum is accurate
if ( check != 0 ) {
    Console.WriteLine( "Error in the checksum" );
}

If you have any questions / comments / corrections, post them in the forums.

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 15 years, 11 months ago on February 4, 2010

Comments have now been turned off for this post

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