Function CalcCRC16(const Buffer: array of byte; inCRC16: Word) : Word;
const
Mask: Word = $A001;
var
N, I: Integer;
B: Byte;
begin
for I := Low(Buffer) to High(Buffer) do
begin
B := Buffer[I];
inCRC16 := inCRC16 xor B;
for N := 1 to 8 do
if (inCRC16 and 1) > 0 then
inCRC16 := (inCRC16 shr 1) xor Mask
else
inCRC16 := (inCRC16 shr 1);
end;
Result := inCRC16;
end;
function FileCRC16(const FileName: string; var CRC16: Word; StartPos: Int64 = 0;
Len: Int64 = 0): Boolean;
const
csBuff_Size = 4096;
type
TBuff = array[0..csBuff_Size - 1] of Byte;
var
Handle: THandle;
ReadCount: Integer;
Size: Int64;
Count: Int64;
Buff: TBuff;
begin
Handle := CreateFile(PChar(FileName), GENERIC_READ,
FILE_SHARE_READ, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
Result := Handle <> INVALID_HANDLE_VALUE;
if Result then
try
Int64Rec(Size).Lo := GetFileSize(Handle, @Int64Rec(Size).Hi);
if Size < StartPos + Len then
begin
Result := False;
Exit;
end;
if Len > 0 then
Count := Len
else
Count := Size - StartPos;
CRC16 := not CRC16;
SetFilePointer(Handle, Int64Rec(StartPos).Lo, @Int64Rec(StartPos).Hi, FILE_BEGIN);
while Count > 0 do
begin
if Count > SizeOf(Buff) then
ReadCount := SizeOf(Buff)
else
ReadCount := Count;
ReadFile(Handle, Buff, ReadCount, LongWord(ReadCount), nil);
CRC16 := CalcCRC16(Buff, CRC16);
Dec(Count, ReadCount);
end;
CRC16 := not CRC16;
finally
CloseHandle(Handle);
end;
end;
Beispiel :
procedure TForm1.Button1Click(Sender: TObject);
var
CRC16: Word;
begin
CRC16 := 0;
if OpenDialog1.Execute then
begin
if FileCRC16(OpenDialog1.FileName, CRC16) then
Label1.Caption := (IntToHex(CRC16, 4));
end;
end;
Beispiel 2 :
procedure TForm1.Button2Click(Sender: TObject);
var
s: String;
buff: packed array of byte;
i: Integer;
begin
case RadioGroup1.ItemIndex of
0: begin // FÜR DIE LANGE EINER DATEI
s := Label1.Caption;
SetLength(buff, Length(s));
for i := 0 to (Length(s))-1 do buff[i] := Byte(Ord(s[i+1]));
Label1.Caption := (IntToHex(CalcCRC16(buff, Word($0000)), 4));
end;
1: begin // FÜR DIE BYTES EINER DATEI
s := Label1.Caption;
SetLength(buff, Length(s) div 2);
for i := 0 to (Length(s) div 2)-1 do
buff[i] := Byte(StrToInt('$'+s[i*2+1]+s[i*2+2]));
Label1.Caption := (IntToHex(CalcCRC16(buff, Word($0000)), 4));
end;
end;
end;
Keine Kommentare:
Kommentar veröffentlichen