The JavaScript is an over-complicated version of the crc32() algorithm as implemented in the zlib/zip library.
It is overcomplicated because of JavaScript itself, which is too high level to process as expected such bit-oriented process. For instance, all those crc = crc ^ (-1)
are to force the content to be 32 bit unsigned, which is not needed in Delphi: you just use a cardinal
variable. The fact that it uses a string table is also something awfull, but pretty common in the javascript work.
The easiest is to use the version shipped with the ZLib.pas
unit.
Here is a short version of this crc32() in pure pascal, using not a fixed table but a once-generated table.
var
crc32Tab : array [0..255] of cardinal;
{
Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
x (which is shifting right by one and adding x^32 mod p if the bit shifted
out is a one). We start with the highest power (least significant bit) of
q and repeat for all eight bits of q.
The table is simply the CRC of all possible eight bit values. This is all
the information needed to generate CRC's on data a byte at a time for all
combinations of CRC register values and incoming bytes.
}
procedure InitCrc32Tab;
var i,n,crc: cardinal;
begin // this code is 49 bytes long, generating a 1KB table
for i := 0 to 255 do begin
crc := i;
for n := 1 to 8 do
if (crc and 1)<>0 then
// $edb88320 from polynomial p=(0,1,2,4,5,7,8,10,11,12,16,22,23,26)
crc := (crc shr 1) xor $edb88320 else
crc := crc shr 1;
CRC32Tab[i] := crc;
end;
end;
function UpdateCrc32(aCRC32: cardinal; inBuf: pointer; inLen: integer) : cardinal;
var i: integer;
begin
result := not aCRC32;
for i := 1 to inLen do begin
result := crc32Tab[byte(result xor pByte(inBuf)^)] xor (result shr 8);
inc(PByte(inBuf));
end;
result := not result;
end;
You will find several other versions (also enhanced for speed) in our source code repository.