CRC-CCITT (0xFFFF) function?

Dels picture Dels · Feb 28, 2011 · Viewed 13.2k times · Source

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;
 }

Answer

Barry Kelly picture Barry Kelly · Feb 28, 2011
  • 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