在 Delphi 中将字节大小转换为 KB、MB、GB 的正确方法是什么。
问问题
7219 次
2 回答
10
我想你想要一个德尔福解决方案。尝试这个
uses
Math;
function ConvertBytes(Bytes: Int64): string;
const
Description: Array [0 .. 8] of string = ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
var
i: Integer;
begin
i := 0;
while Bytes > Power(1024, i + 1) do
Inc(i);
Result := FormatFloat('###0.##', Bytes / IntPower(1024, i)) + ' ' + Description[i];
end;
于 2015-05-30T18:07:29.460 回答
7
像这样:
KB := Bytes / 1024;
MB := Bytes / (1024*1024);
GB := Bytes / (1024*1024*1024);
这会产生浮点值。如果您需要整数值,则将这些值四舍五入:
KB := Round(Bytes / 1024);
MB := Round(Bytes / (1024*1024));
GB := Round(Bytes / (1024*1024*1024));
或使用整数除法截断:
KB := Bytes div 1024;
MB := Bytes div (1024*1024);
GB := Bytes div (1024*1024*1024);
当然,我不知道你所说的“正确”是什么意思。如果您正在寻找一个将整数字节转换为人类可读字符串的函数,您可以使用以下代码:
const
OneKB = 1024;
OneMB = OneKB * OneKB;
OneGB = OneKB * OneMB;
OneTB = Int64(OneKB) * OneGB;
type
TByteStringFormat = (bsfDefault, bsfBytes, bsfKB, bsfMB, bsfGB, bsfTB);
function FormatByteString(Bytes: UInt64; Format: TByteStringFormat = bsfDefault): string;
begin
if Format = bsfDefault then begin
if Bytes < OneKB then begin
Format := bsfBytes;
end
else if Bytes < OneMB then begin
Format := bsfKB;
end
else if Bytes < OneGB then begin
Format := bsfMB;
end
else if Bytes < OneTB then begin
Format := bsfGB;
end
else begin
Format := bsfTB;
end;
end;
case Format of
bsfBytes:
Result := SysUtils.Format('%d bytes', [Bytes]);
bsfKB:
Result := SysUtils.Format('%.1n KB', [Bytes / OneKB]);
bsfMB:
Result := SysUtils.Format('%.1n MB', [Bytes / OneMB]);
bsfGB:
Result := SysUtils.Format('%.1n GB', [Bytes / OneGB]);
bsfTB:
Result := SysUtils.Format('%.1n TB', [Bytes / OneTB]);
end;
end;
于 2015-05-30T17:15:47.203 回答