§ July 28, 2012

A Standard CRC-16 and CRC-16 Kermit implementation in C#

Been a while since I posted anything, but here's an update to my original CRC-16 class that does CRC-16 with CRC-CCITT Kermit code that I posted over on Stack Overflow a while ago. Unlike the code over there this doesn't have a static look-up table (feel free to get the code from over there if you wanted the static table, but I'm actually not too fond of static look-up tables on example source code though they are more efficient).

using System;

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16 {
    readonly ushort[] table = new ushort[256];

    public ushort ComputeChecksum( params byte[] bytes ) {
        ushort crc = 0;
        for(int i = 0; i < bytes.Length; ++i) {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

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

    public Crc16( Crc16Mode mode ) {
        ushort polynomial = (ushort)mode;
        ushort value;
        ushort temp;
        for(ushort i = 0; i < table.Length; ++i) {
            value = 0;
            temp = i;
            for(byte j = 0; j < 8; ++j) {
                if(((value ^ temp) & 0x0001) != 0) {
                    value = (ushort)((value >> 1) ^ polynomial);
                }else {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}
If you need for this code to be CLS compliant, you can change the method signature's return type from ushort to int and it will operate the same (the ushort crc value will be implicitly converted from ushort to int)

Links to the other C# CRC implementations the original CRC-16 implementation, CRC16-CCITT, CRC-32, and CRC-8

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 12 years, 7 months ago on July 28, 2012

Comments have now been turned off for this post

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