I have this code sample of CRC-16 calculation and I want to convert it to C#. It have to stay with the same logic because it works with other machines.
I saw this crc16 from c to c# but it doesn't work (different result), maybe because of the variable types.
The original code is: Input char = 'A', remainder = 0, Output = 390
#define CRC_POLYNOMIAL 0x8005 /* CRC polynomial */
short Calculate_CRC ( char ch, short remainder ){
char *ch_ptr;
int i;
// the different part
ch_ptr = (char*)&remainder;
*(ch_ptr+1) = *(ch_ptr+1) ^ ch; /* exclusive or ch with msb of remainder */
for (i=0; i<=7; i++)
if (remainder < 0)
{ /* msb of remainder = 1 */
remainder = remainder << 1;
remainder = remainder ^ CRC_POLYNOMIAL;
}
else
remainder = remainder << 1;
return (remainder);
}
and my code is: Input char = 'A', remainder = 0, Output = 514
static public ushort func(byte ch, ushort remainder, int f) {
// the different part
byte[] rawCrc = new byte[2];
rawCrc[0] = (byte)(remainder & 0x00FF);
rawCrc[1] = (byte)((remainder >> 8) & 0x00FF);
rawCrc[0] ^= ch;
remainder &= (byte)(rawCrc[0]);
for (int i = 0; i <= 7; i++)
if ((remainder & (0x8000)) == 0) { /* msb of remainder = 1 */
remainder <<= 1;
remainder ^= POL;
}
else
remainder <<= 1;
return remainder;
}
The result is different but as I can see, my code still doing the xor with the msb as needed.
How can I fix it?
TIA