Total Download 代码的错误结果

Incorrect Result of Total Download's Code

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

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;

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

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;