How to convert any digital storage unit into all others (B, KB, MB, GB, TB, PB, EB, ZB, YB) in Pascal

1 Answer

0 votes
program StorageUnitConverter;

uses
    Math, SysUtils;

{
    Digital storage conversion table:
    Each unit is a power of 1024 relative to bytes.

    Bytes (B)      = 1024^0
    Kilobytes (KB) = 1024^1
    Megabytes (MB) = 1024^2
    Gigabytes (GB) = 1024^3
    Terabytes (TB) = 1024^4
    Petabytes (PB) = 1024^5
    Exabytes (EB)  = 1024^6
    Zettabytes (ZB)= 1024^7
    Yottabytes (YB)= 1024^8
}

// Convert any unit to bytes using its exponent
function ToBytes(value: Double; exponent: Integer): Double;
begin
    // 1024^exponent gives the multiplier for the unit
    ToBytes := value * Power(1024.0, exponent);
end;

// Convert bytes to any unit using its exponent
function FromBytes(bytes: Double; exponent: Integer): Double;
begin
    FromBytes := bytes / Power(1024.0, exponent);
end;

// Print all conversions from a given byte value
procedure PrintAll(bytes: Double);
const
    Names: array[0..8] of String = (
        'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'
    );
var
    exp: Integer;
begin
    for exp := 0 to 8 do
        WriteLn(Format('%8s: %.6f', [Names[exp], FromBytes(bytes, exp)]));
end;

var
    value: Double;
    unitStr: String;
    exponent: Integer;
    bytes: Double;

begin
    WriteLn('Digital Storage Unit Converter');
    WriteLn;

    Write('Enter value: ');
    ReadLn(value);

    Write('Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ');
    ReadLn(unitStr);

    // Map unit string to exponent
    exponent := -1;

    if unitStr = 'B'  then exponent := 0;
    if unitStr = 'KB' then exponent := 1;
    if unitStr = 'MB' then exponent := 2;
    if unitStr = 'GB' then exponent := 3;
    if unitStr = 'TB' then exponent := 4;
    if unitStr = 'PB' then exponent := 5;
    if unitStr = 'EB' then exponent := 6;
    if unitStr = 'ZB' then exponent := 7;
    if unitStr = 'YB' then exponent := 8;

    if exponent < 0 then
    begin
        WriteLn('Unknown unit.');
        Halt(1);
    end;

    // Convert input to bytes
    bytes := ToBytes(value, exponent);

    // Print all conversions
    WriteLn;
    WriteLn('Converted values:');
    PrintAll(bytes);
end.


{
run:

Digital Storage Unit Converter

Enter value: 360
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): PB

Converted values:
   Bytes: 405323966463344640.000000
      KB: 395824185999360.000000
      MB: 386547056640.000000
      GB: 377487360.000000
      TB: 368640.000000
      PB: 360.000000
      EB: 0.351562
      ZB: 0.000343
      YB: 0.000000

}

 



answered Aug 27 by avibootz
edited Aug 27 by avibootz

Related questions

...