Search code examples
c#variablescrc

What's the importance of the Offset variable in this algorithm?


What's the meaning of this variable named Offset in this algorithm ? It's declared in the second calcCrc16 parameter. For me it's useless bcause it's aways zero and it's used in a sum.

this algorithm generates a crc-16. I'm trying to understand this algorithm bcause a have to create a algorithm that verify crc-16, and i want to use this code as base.

public sealed class CRC
{
    private readonly int _polynom;

    public static readonly CRC Default = new CRC(0xA001);

    public CRC(int polynom)
    {
        _polynom = polynom;
    }

    public int CalcCrc16(byte[] buffer)
    {
        return CalcCrc16(buffer, 0, buffer.Length, _polynom, 0);
    }

    public static int CalcCrc16(byte[] buffer, int offset, int bufLen, int polynom, int preset)
    {
        preset &= 0xFFFF;
        polynom &= 0xFFFF;

        var crc = preset;
        for (var i = 0; i < (bufLen + 2); i++)
        {
            var data = buffer[(i + offset) % buffer.Length] & 0xFF;
            crc ^= data;
            for (var j = 0; j < 8; j++)
            {
                if ((crc & 0x0001) != 0)
                {
                    crc = (crc >> 1) ^ polynom;
                }
                else
                {
                    crc = crc >> 1;
                }
            }
        }
        return crc & 0xFFFF;
    }
}

Solution

  • I created a simple example, using a small 4 byte message (in a 6 byte buffer):

    using System;
    namespace crc16
    {
        class Program
        {
            private static ushort Crc16(byte[] bfr, int bfrlen)
            {
                ushort crc = 0;
                for (int i = 0; i < bfrlen; i++)
                {
                    crc ^= bfr[i];
                    for (int j = 0; j < 8; j++)
                        // assumes twos complement math
                        crc = (ushort)((crc >> 1)^((0 - (crc&1)) & 0xa001));
                }
                return crc;
            }
    
            static void Main(string[] args)
            {
                ushort crc;
                byte[] data = new byte[6] {0x11, 0x22, 0x33, 0x44, 0x00, 0x00};
                crc = Crc16(data, 4);           // generate crc
                data[4] = (byte)(crc & 0xff);   // append crc (lsb first)
                data[5] = (byte)(crc >> 8);
                crc = Crc16(data, 6);           // verify crc;
                Console.WriteLine("{0:X4}", crc);
                return;
            }
        }
    }