Search code examples
c#delphicrckermit

Convert CRC-CCITT Kermit 16 DELPHI code to C#


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.


Solution

  • 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[].