[fpc-pascal] Calculating CRC16?

Jean SUZINEAU jean.suzineau at wanadoo.fr
Tue Oct 25 12:10:47 CEST 2022


I couldn't verify the code but it should be  relatively close to your  
c++ example. Not sure of the width of int type, I supposed it's 16 bits 
wide:

function CRC16( crc: Word; buf: PByte; len: Word; Poly:Word=$A001): Word;
var
    pos: Word;
    i: Word;
begin
      for pos:= 0 to len-1
      do
        begin
        crc:= crc xor Word(buf[pos]);    // * XOR byte into least sig. byte of crc
        // * Loop over each bit
        for i:= 8 downto 1
        do
          begin
          // * If the LSB is set
          if ((crc and $0001) <> 0)
          then
              begin
              // * Shift right and XOR 0xA001
              crc:= crc shr 1;
                 crc:= crc xor Poly;
              end
          // * Else LSB is not set
          else
              // * Just shift right
              crc:= crc shr 1;
          end;
        end;
       Result:= crc;
end;
var
    S: String;
begin
      Readln( S);
      WriteLn( IntToHex( CRC16( 0, PByte(@S[1]), Length(S), $8005), 4));
end.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20221025/225fafb6/attachment.htm>


More information about the fpc-pascal mailing list