4

I've been searching the net for a C# implementation of the 4-bit cyclic redundancy check (CRC-4-ITU) but so far I've been unsuccessful.

Is there anyone who's able to give me a reference implementation of CRC-4-ITU? Preferrably with the standard polynomial if there is a standard polynomial (I've read the spec pointed to by wikipedia as the CRC4 spec without finding a definition of the polynomial).

I'd also really appreciate some sort of test suite or test data to verify a CRC4 implementation.

Thanks!

Markus Olsson
  • 22,402
  • 9
  • 55
  • 62
  • 3
    Jesus Christ Google is scary. This is the 6th Google Result for "CRC-4-ITU" and it was indexed 7 minutes after it was posted. – Tom Ritter Dec 02 '09 at 17:47
  • 1
    Google and SO have some sort of arrangement. It might simply be the SiteMap file, and the fact that SO has a high GoogleRank, so it's more important than MyLittleDorkySite.com. – Robert Harvey Dec 02 '09 at 17:49

1 Answers1

3

The Cyclic Redundancy Check article at Wikipedia says the polynomial is x^4 + x + 1. There is also a pretty good description of how the checksum is computed.

Here is an algorithm for CRC16. I know it's not what you asked for, but it should be relatively straightforward to adapt it for 4 bits.

   public ushort calculate(byte[] bytes)
    {
        int crc = 0xFFFF; // initial value
        // loop, calculating CRC for each byte of the string
        for (int byteIndex = 0; byteIndex < bytes.Length; byteIndex++)
        {
            ushort bit = 0x80; // initialize bit currently being tested
            for (int bitIndex = 0; bitIndex < 8; bitIndex++)
            {
                bool xorFlag = ((crc & 0x8000) == 0x8000);
                crc <<= 1;
                if (((bytes[byteIndex] & bit) ^ (ushort)0xff) != (ushort)0xff)
                {
                    crc = crc + 1;
                }
                if (xorFlag)
                {
                    crc = crc ^ 0x1021;
                }
                bit >>= 1;
            }
        }
        return (ushort)crc;
    }

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24775723.html

Also, there is this guide to computing checksums:

http://www.ross.net/crc/download/crc_v3.txt

"Everything you wanted to know about CRC algorithms, but were afraid to ask for fear that errors in your understanding might be detected."

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • This awesome tool generates C code for arbitrary polynomials! (You want 10011) Should be easy to convert to C#: https://ghsi.de/CRC/index.php – Robert Calhoun Aug 12 '15 at 00:35
  • Above mentioned page is moved to: http://www.ghsi.de/pages/subpages/Online%20CRC%20Calculation/ – stardust Nov 19 '19 at 15:32