总下载代码的结果不正确

时间:2015-05-24 00:33:43

标签: delphi delphi-7

我使用以下代码显示总下载和上传。当累积下载超过2 GB时,会出现问题,结果是位数:

var
  Form1: TForm1;
  Downloaded, Uploaded:integer;

implementation

{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if Downloaded < 1024 then
  Recv.Caption           := FormatFloat(' + Recv: #,0 Bit',Downloaded)
  else if (Downloaded > 1024) and (Downloaded < 1048576) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Kb',Downloaded/1024)
  else if (Downloaded > 1048576) and (Downloaded < 1073741824) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Mb',Downloaded/1048576)
  else if (Downloaded > 1073741824) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Gb', Downloaded/1073741824);

  if Uploaded < 1024 then
  Sent.Caption               := FormatFloat(' + Sent: #,0 Bit',Uploaded)
  else if (Uploaded > 1024) and (Uploaded < 1048576) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Kb',Uploaded/1024)
  else if (Uploaded > 1048576) and (Uploaded < 1073741824) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Mb',Uploaded/1048576)
  else if (Uploaded > 1073741824) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Gb', Uploaded/1073741824);
end;

任何人都可以解释为什么它会返回错误的结果,更重要的是,如何修复它以便返回正确的结果?非常感谢你......

1 个答案:

答案 0 :(得分:9)

Integer无法保存大于2GB的值(MaxInt为2147483647,即~1.99 GB)。如果你试图超过它,它会溢出并变为负数。您需要改为使用Int64

此外,您应该使用BBytes代替Bit。你没有下载位,你正在下载字节。

试试这个:

var
  Form1: TForm1;
  Downloaded, Uploaded: Int64;

implementation

{$R *.dfm}

function FormatBytes(ABytes: Int64): string;
begin
  if ABytes < 1024 then
    Result := FormatFloat('#,0 B', ABytes)
  else if ABytes < 1048576 then
    Result := FormatFloat('#,##0.00 Kb', ABytes / 1024)
  else if ABytes < 1073741824 then
    Result := FormatFloat('#,##0.00 Mb', ABytes / 1048576)
  else if ABytes < 1099511627776 then
    Result := FormatFloat('#,##0.00 Gb', ABytes / 1073741824)
  else
    Result := FormatFloat('#,##0.00 Tb', ABytes / 1099511627776);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Recv.Caption := ' + Recv: ' + FormatBytes(Downloaded);
  Send.Caption := ' + Sent: ' + FormatBytes(Uploaded);
end;