Search code examples
c#ccrccrc16

C to C# CRC calculation convertor


I have a code in C which I need to rewrite it in c#

however in C# there are not pointers

how can I do this conversion?

Thank for all answers

unsigned int CCITT_CRC_TAB[256] = {         // CCITT CRC-16 polynomial table
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
};
unsigned int CalcCrc16( unsigned int* ptr_res , unsigned char * 
BufStart,unsigned char BufLen)
{
 unsigned int CRCres,V1; // 16 bit var
 unsigned char * BufPtr;  // 8 bit var

    BufPtr = BufStart;
    for(CRCres = 0 ;BufPtr < (BufStart + BufLen) ;BufPtr++)
  {
    V1 = (unsigned int)((CRCres>>8)^ *BufPtr);
    CRCres  = (unsigned int)((CRCres>>8)^ CCITT_CRC_TAB[V1]);
  }

*ptr_res = CRCres;
}

Solution

  • The C# way (assuming that the callers will be migrated as well or are allready C#):

    uint CalcCrc16(byte[] BufStart, byte BufLen)
    {
        uint CRCres = 0, V1 = 0; // 16 bit var
        for(int i = 0 ; i < BufLen; i++)
        {
            V1 = (uint)((CRCres>>8) ^ BufStart[i]);
            CRCres  = (uint)((CRCres>>8)^ CCITT_CRC_TAB[V1]);
        }
        return CRCres;
    }