Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRC-CCITT (0xFFFF) function?

Tags:

delphi

crc

Can someone help me with Delphi implementation of CRC-CCITT (0xFFFF)?

Already get the Java version, but confusing on how to port it to Delphi

public static int CRC16CCITT(byte[] bytes) {
    int crc = 0xFFFF;          // initial value
    int polynomial = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 

    for (byte b : bytes) {
        for (int i = 0; i < 8; i++) {
            boolean bit = ((b   >> (7-i) & 1) == 1);
            boolean c15 = ((crc >> 15    & 1) == 1);
            crc <<= 1;
            if (c15 ^ bit) crc ^= polynomial;
         }
    }

    crc &= 0xffff;
    //System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
    return crc;
}

and for PHP implementation

<?php
function crc16($data)
 {
   $crc = 0xFFFF;
   for ($i = 0; $i < strlen($data); $i++)
   {
     $x = (($crc >> 8) ^ ord($data[$i])) & 0xFF;
     $x ^= $x >> 4;
     $crc = (($crc << 8) ^ ($x << 12) ^ ($x << 5) ^ $x) & 0xFFFF;
   }
   return $crc;
 }
like image 776
Dels Avatar asked Feb 28 '11 08:02

Dels


2 Answers

  • 0xFFFF translates to $FFFF
  • & translates to and
  • ^ translates to xor
  • << translates to shl
  • >> translates to shr
  • x ^= y translates to x := x xor y, similar for &=, <<=, etc.

These operators generally have higher precedence in Delphi so they usually need to have their arguments parenthesized.

I'm quite sure that there are plenty of other implementations of CRC16 etc. for Delphi, see e.g. Improve speed on Crc16 calculation

like image 180
Barry Kelly Avatar answered Oct 05 '22 08:10

Barry Kelly


function CRC16CCITT(bytes: TBytes): Word;
const
  polynomial = $1021;   // 0001 0000 0010 0001  (0, 5, 12)
var
  crc: Word;
  I, J: Integer;
  b: Byte;
  bit, c15: Boolean;
begin
  crc := $FFFF; // initial value
  for I := 0 to High(bytes) do
  begin
    b := bytes[I];
    for J := 0 to 7 do
    begin
      bit := (((b shr (7-J)) and 1) = 1);
      c15 := (((crc shr 15) and 1) = 1);
      crc := crc shl 1;
      if ((c15 xor bit) <> 0) then crc := crc xor polynomial;
    end;
  end;
  Result := crc and $ffff;
end;
like image 37
Remy Lebeau Avatar answered Oct 05 '22 09:10

Remy Lebeau