How could I use this function for calculating CHECKSUM

Viewed 303

I'm trying to calculate checksum for serial communication. so I made a byte array for databuffer. I don't know how to use this byte array of databuffer to this fuction. because this function's parameter type is byte pointer. How do I use this function?

byte[] arrayForChecksum // for databuffer

// calculating a checksum for C#
public unsafe static ushort CalcCRC(byte * pDataBuffer, uint usDataLen)
{
        byte nTemp;
        ushort wCRCWord = 0xFFFF;

        while ((usDataLen--) != 0)
        {
            nTemp = (byte)(wCRCWord ^*pDataBuffer++);
            wCRCWord >>= 8;
            wCRCWord ^= TABLE_CRCVALUE[nTemp];
        }

        return wCRCWord;
}


// original code in C
unsigned short CalcCRC(unsigned char* pDataBuffer, unsigned long usDataLen)
{       
    unsigned char nTemp;
    unsigned short wCRCWord = 0xFFFF;

    while (usDataLen--)
   {
        nTemp = wCRCWord ^ *(pDataBuffer++);
        wCRCWord >>= 8;
        wCRCWord ^= TABLE_CRCVALUE[nTemp];
    }

    return wCRCWord;
}
1 Answers

You can use checksum for anything. For example, you can convert the text you will get from the database to byte array and calculate the checksum value.

public class Crc16
{
    private const ushort polynomial = 0xA001;
    private static readonly ushort[] refTable = new ushort[256];

    public Crc16()
    {
        GenerateReferenceTable();
    }

    private void GenerateReferenceTable()
    {
        ushort value;
        ushort temp;

        for (ushort i = 0; i < refTable.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;
            }

            refTable[i] = value;
        }
    }

    public ushort Calculate(byte[] bytes)
    { 
        ushort crc = 0; 

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

        return crc;
    }
}

Usage:

byte[] bytes = new byte[] { 0, 1, 2, 3, 204, 120 }; 
Crc16 crc16 = new Crc16();
ushort checksum = crc16.Calculate(bytes);


string data = "Calculate Checksum";
byte[] bytesFromString = Encoding.ASCII.GetBytes(data);
ushort checksumForString = crc16.Calculate(bytesFromString); 

You can also check out my project.

https://github.com/hidayetcolkusu/ChecksumManager

Related