CRC-CCITT(0xFFFF)功能?

Del*_*els 5 delphi crc

有人可以帮助我使用Delphi实现CRC-CCITT(0xFFFF)吗?

已经获得Java版本,但是如何将其移植到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;
}
Run Code Online (Sandbox Code Playgroud)

并为PHP实现

<?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;
 }
Run Code Online (Sandbox Code Playgroud)

Bar*_*lly 12

  • 0xFFFF 翻译成 $FFFF
  • & 翻译成 and
  • ^ 翻译成 xor
  • << 翻译成 shl
  • >> 翻译成 shr
  • x ^= y转化为x := x xor y类似的&=,<<=等等.

这些运算符通常在Delphi中具有更高的优先级,因此它们通常需要将其参数括号括起来.

我很确定Delphi有很多其他的CRC16等实现,例如参见Crc16计算的提高速度


Rem*_*eau 9

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;
Run Code Online (Sandbox Code Playgroud)


Tri*_*enT 5

您可以在Delphi Encryption Compendium(DEC)组件中找到一个.

5校验和(CRC32,CRC16-CCITT,CRC16-Standard ......)

http://blog.digivendo.com/2008/11/delphi-encryption-compendium-dec-52-for-d2009-released/


Del*_*els 4

我发现一些有效的代码:

function crc16(Buffer:String;Polynom,Initial:Cardinal):Cardinal;
var
  i,j: Integer;
begin
Result:=Initial;
for i:=1 to Length(Buffer) do begin
  Result:=Result xor (ord(buffer[i]) shl 8);
  for j:=0 to 7 do begin
    if (Result and $8000)<>0 then Result:=(Result shl 1) xor Polynom
    else Result:=Result shl 1;
    end;
  end;
Result:=Result and $ffff;
end;
Run Code Online (Sandbox Code Playgroud)

来源: http: //www.miscel.dk/MiscEl/CRCcalculations.html