总下载代码的错误结果
我使用以下代码显示下载和上传的总数。当累积下载量超过2 GB时,就会出现问题,其结果是位数:
I use the following code to display the total download and upload. The problem arises when the cumulative download exceeds 2 GB, the result being the number of bits:
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;
谁能解释为什么返回的结果不正确,更重要的是如何解决它,以便返回结果正确的结果?非常感谢...
Can anyone explain why it is returning the incorrect result and more importantly, how to fix it so it returns the correct result ? Thank you so much...
整数
不能容纳大于2GB的值( MaxInt
为2147483647,约为1.99 GB)。如果尝试超过该值,它将溢出并变为负数。您需要改用 Int64
。
An Integer
cannot hold a value greater than 2GB (MaxInt
is 2147483647, which is ~1.99 GB). If you try to exceed that, it overflows and becomes negative. You need to use Int64
instead.
此外,您应该使用 B
或 Bytes
,而不是 Bit
。您不是在下载位,而是在下载字节。
Also, you should be using B
or Bytes
instead of Bit
. You are not downloading bits, you are downloading bytes.
尝试一下:
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;