简体   繁体   中英

CRC Calculation Of Byte Array in C#

I am trying to port a piece of code that has been written in C language into C#. The purpose of the code is to calculate the CRC of an array of bytes. But so far I failed. My byte array looks something like this:

data = new byte[] { 0x01, 0x03, 0x00, 0x00, 0x00 };

And the C code I am trying to port to C# is as follows.

unsigned  int  crc_val(unsigned char* data_val, unsigned char data_len) 
{   
    int i;
    unsigned int crc_value=0ffff;
    while(data_len--)
    {
        crc_value^=*data_ val++;
        for(i=0;i<8;i++)
        {
            if(crc_value&0x0001)
                crc_value=(crc_value>> 1)^0xa001;
            else
                crc_value=crc_value>> 1;
        }
    }
    return (crc_value);
 } 

Right now I have this:

private void GetCRC(byte[] message, ref byte[] CRC)
{
    ushort CRCFull = 0xFFFF;
    char CRCLSB;

    for (int i = 0; i < (message.Length) - 2; i++)
    {
        CRCFull = (ushort)(CRCFull ^ message[i]);

        for (int j = 0; j < 8; j++)
        {
            CRCLSB = (char)(CRCFull & 0x0001);
            CRCFull = (ushort)((CRCFull >> 1) & 0xFFFF);
            if (CRCLSB == 1)
                CRCFull = (ushort)(CRCFull ^ 0xA001);
        }
    }
    CRC[1] = (byte)((CRCFull >> 8) & 0xFF);
    CRC[0] = (byte)(CRCFull & 0xFF);
}

Please, please, please... Teach me how this code is written in C#, I am a quick learner and once I see the C# implementation of the above function, I shall pick it up from there and finish my application. I thank you for your attention and wish you all spend a fabulous day.

Some tips:

  • unsigned char* -> byte[] or Span<byte> or IEnumerable<byte>

  • There is no need for a separate data_len parameter, just about all c# collections know their length, the only real exception would be raw pointers, but there is little need for those since the introduction of Span<T>

  • 0ffff -> looks like a typo, I assume 0xffff is intended

  • change your loop to a foreach, or for-loop ie

    foreach(var b in data_val){ crc_value^=b; ... }
  • bit operations should work the same way

  • You need to figure out what the length of the datatype is, unsigned int is minimum 16 bits, but may be 32 bit. In c# an uint is 32 bits, and ushort is 16 bit.

  • If you need to convert numbers to byte[] or vice versa, see BitConverter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM