-2

I'm a junior developer. I got a converting problem with below CRC16 check algorithm. I have to convert below C/C++ CRC-16 algorithm to C# algorithm. here is CRC-16 algorithm.

unsigned short Crc16(unsigned char* rdata, unsigned int len){
    int i, n;
    unsigned short wCh, wCrc = 0XFFFF;

    for (i = 0; i < len; i++){
        wCh = (uword)*(rdata + i);

        for (n = 0; n < 8; n++){
            if ((wCh^wCrc) & 0x0001)
                wCrc = (wCrc >> 1) ^ 0xA001;
            else
                wCrc >>= 1;
            wCh >>= 1;
        }
    }
    return wCrc;
}

I got a stuck at this problem. I tried to convert this algorithm directly on my C#(winform) project but can not solve type matching problem. (ex, unsigned => ushort, unsigned char* => ???? 'I have no idea')

also, I tried to implement above code as a DLL and then import DLL file on my C# project. But still can not solve type matching problem. (ex, [DllImport("Crc_dll.dll")] public static extern ushort Crc16(unsigned char* rdata, unsigned int len); => how to convert unsigned char*, unsigned int??)

If anybody know, could you help me please?

Since above algorithm is given from client, I can't use other crc16 algorithms.

1 Answers1

1

unsigned char* rdata should just be a byte[] rdata in C#. Also an integer is not implicitly converted to bool in C# (#1), and wide results are not implicitly converted to a narrow destination type (#2).

ushort Crc16(byte[] rdata, int len){
    int i, n;
    ushort wCh, wCrc = 0XFFFF;

    for (i = 0; i < len; i++){
        wCh = rdata[i];

        for (n = 0; n < 8; n++){
            if (((wCh^wCrc) & 0x0001) != 0) // #1
                wCrc = (ushort)((wCrc >> 1) ^ 0xA001); // #2
            else
                wCrc >>= 1;
            wCh >>= 1;
        }
    }
    return wCrc;
}
harold
  • 61,398
  • 6
  • 86
  • 164