Convert CRC-CCITT Kermit 16 DELPHI code to C#

5.8k views Asked by At

I am working on a function that will give me a Kermit CRC value from a HEX string. I have a piece of code in DELPHI. I am a .NET developer and need the code in C#.

function CRC_16(cadena : string):word; 
var 
valuehex : word; 
i: integer; 
CRC : word; 
Begin 
   CRC := 0; 
   for i := 1 to length(cadena) do 
   begin 
      valuehex := ((ord(cadena[i]) XOR CRC) AND $0F) * $1081; 
      CRC := CRC SHR 4; 
      CRC := CRC XOR valuehex; 
      valuehex := (((ord(cadena[i]) SHR 4) XOR LO(CRC)) AND $0F); 
      CRC := CRC SHR 4; 
      CRC := CRC XOR (valuehex * $1081); 
   end; 
  CRC_16 := (LO(CRC) SHL 8) OR HI(CRC); 
end;

I got the code from this webpage: Kermit CRC in DELPHI

I guess that Delphi function is correct. If any one can please convert the code to C# that will be great. I tried to convert to C#, but got lost in WORD data type and the LO function of Delphi. Thank you all.

2

There are 2 answers

3
dtb On BEST ANSWER

From MSDN forums:

static long ComputeCRC(byte[] val)
{
    long crc;
    long q;
    byte c;
    crc = 0;
    for (int i = 0; i < val.Length; i++)
    {
        c = val[i];
        q = (crc ^ c) & 0x0f;
        crc = (crc >> 4) ^ (q * 0x1081);
        q = (crc ^ (c >> 4)) & 0xf;
        crc = (crc >> 4) ^ (q * 0x1081);
    }
    return (byte)crc << 8 | (byte)(crc >> 8);
}

Use Encoding.ASCII.GetBytes(string) to convert a string to a byte[].

2
Andreas Rejbrand On

A word is a 16-bit unsigned integer (which can store the values 0..65535).

Lo returns the low-order byte of an integer. So if the integer is 0x7B41AF, for example, lo will return 0xAF.