Click here to Skip to main content
15,885,874 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
How to calculate CRC ccitt xmodem with polynomial 1021 in C# 


What I have tried:

C#
ushort result = Crc16Ccitt("*233050003LED");

private ushort Crc16Ccitt(string strInput)
        {
            byte[] bytes= Encoding.ASCII.GetBytes(strInput);
            const ushort poly = 4129;
            ushort[] table = new ushort[256];
            ushort initialValue = 0xffff;
            ushort temp, a;
            ushort crc = initialValue;
            for (int i = 0; i < table.Length; ++i)
            {
                temp = 0;
                a = (ushort)(i << 8);
                for (int j = 0; j < 8; ++j)
                {
                    if (((temp ^ a) & 0x8000) != 0)
                        temp = (ushort)((temp << 1) ^ poly);
                    else
                        temp <<= 1;
                    a <<= 1;
                }
                table[i] = temp;
            }
            for (int i = 0; i < bytes.Length; ++i)
            {
                crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
            }
            return crc;
        }
Posted
Updated 28-Sep-17 21:46pm
v2

1 solution

The posted code correctly computes the CRC-16-CCITT with initial value 0xFFFF.
See On-line CRC calculation and free library[^] and microcontroller - CRC16 checksum: HCS08 vs. Kermit vs. XMODEM - Stack Overflow[^].

If you need the XModem one then change from
Quote:
ushort initialValue = 0xffff;
to
C#
ushort initialValue = 0;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900