Algorithme CRC – 16 – CCITT

Un autre CRC dans ma bibliothèque est le CRC-16-CCITT ou plus court le CRC-CCITT, je suis tombé sur son utilisation dans
un tourniquet automatique. On peux le retrouver dans X.25, V.41, HDLC FCS, XMODEM, Bluetooth, PACTOR, SD et autres.

Utilisation: crc := CRC_CRTITT(packet);

unit CRC_CCITT;

interface

const
P_CCITT= $1021;
function CRC_CRTITT(packet : tbytes):word;

implementation

var
crc_table: array[0..255] of word;
crc_table_init: boolean = false;

procedure SendByte(B: Byte; var crc: word);
var
tmp, c: word;
begin
c  := $00ff and B;

tmp := (crc shr 8) xor c;
crc := (crc shl 8) xor crc_table[tmp];
end;

procedure MakeTable;
var i, j: Integer;
crc, c: word;
begin
for i := 0 to 255 do begin
crc := 0;
c := i shl 8;
for j := 0 to 7 do begin
if ((crc xor c) and $8000) > 0  then crc := ( crc shl 1 ) xor P_CCITT
else crc := crc shl 1;
c := c shl 1;
end;
crc_table[i] := crc;
end;
crc_table_init := TRUE;
end;

function CRC_CRTITT(packet : tbytes):word;
var
i: integer;
crc: word;
Begin
crc := 0;
if not crc_table_init then MakeTable;

for i := 0 to length(packet)-1 do
begin
SendByte(packet[i], crc);
end;
CRC_CRTITT := CRC;
end;
end.

Leave a Reply

Your email address will not be published. Required fields are marked *