C
cjsam
Unregistered / Unconfirmed
GUEST, unregistred user!
2边通讯,取一个文件的累加和做个简单的校验,每次读4个字节来累加,初始判断,不够4个字节的整除的,用0来补位.用2个字节来保存累加和.
我下面这个代码,大家帮我看看对吗?如果不对,那有问题,我和客户端的算出来的总是不一样.但是值差的又不是很大.
Function Checksum(filename:string):integer;stdcall;
var
tm:TMemoryStream;
iLen,addLen,i,iB:integer;
str1:string;
Ts:^longint;
allTS:Longint;
begin
if filename='' then
Result:=0;
tm:=TMemoryStream.Create;
str1:='';
try
tm.LoadFromFile(filename);
except
tm.Destroy;
end;
iLen:=tm.Size;
addLen:=iLen mod 4;
//将文件后补0,凑成4的整数倍.
if addLen<>0 then
begin
for i:= 0 to addLen do
str1:=str1+chr($00);
tm.Write(str1[1],addLen);
end;
iB:=tm.Size div 4;
GetMem(Ts, 4);
allTs:=0;
for i:=0 to iB-1 do
begin
tm.Seek(i*4,sofrombeginning);
try
tm.Read(Ts^,4);
except
end;
allTs:=allTs+ts^;
end;
FreeMem(Ts);
tm.Destroy;
Result:=allTs;
end;
我下面这个代码,大家帮我看看对吗?如果不对,那有问题,我和客户端的算出来的总是不一样.但是值差的又不是很大.
Function Checksum(filename:string):integer;stdcall;
var
tm:TMemoryStream;
iLen,addLen,i,iB:integer;
str1:string;
Ts:^longint;
allTS:Longint;
begin
if filename='' then
Result:=0;
tm:=TMemoryStream.Create;
str1:='';
try
tm.LoadFromFile(filename);
except
tm.Destroy;
end;
iLen:=tm.Size;
addLen:=iLen mod 4;
//将文件后补0,凑成4的整数倍.
if addLen<>0 then
begin
for i:= 0 to addLen do
str1:=str1+chr($00);
tm.Write(str1[1],addLen);
end;
iB:=tm.Size div 4;
GetMem(Ts, 4);
allTs:=0;
for i:=0 to iB-1 do
begin
tm.Seek(i*4,sofrombeginning);
try
tm.Read(Ts^,4);
except
end;
allTs:=allTs+ts^;
end;
FreeMem(Ts);
tm.Destroy;
Result:=allTs;
end;