Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

checksum - CRC-4 implementation in C#

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...