正确的方法将大小以字节为单位转换为KB,MB,GB Delphi

时间:2015-05-30 17:04:37

标签: delphi delphi-xe8

在Delphi中将大小(以字节为单位)转换为KB,MB,GB的正确方法是什么。

2 个答案:

答案 0 :(得分:9)

我想你想要一个Delphi解决方案。试试这个

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;

答案 1 :(得分:5)

像这样:

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;