How to correctly convert filesize in bytes into mega or gigabytes?

60,271

Solution 1

1024 is correct for usage in programs.

The reason you may be having differences is likely due to differences in what driveinfo reports as "available space" and what windows considers available space.

Note that only drive manufacturers use 1,000. Within windows and most programs the correct scaling is 1024.

Also, while your compiler should optimize this anyway, this calculation can be done by merely shifting the bits by 10 for each magnitude:

KB = B >> 10
MB = KB >> 10 = B >> 20
GB = MB >> 10 = KB >> 20 = B >> 30

Although for readability I expect successive division by 1024 is clearer.

Solution 2

XKCD has the definite answer:

Single, definitive standard for KB

Solution 3

/// <summary>
/// Function to convert the given bytes to either Kilobyte, Megabyte, or Gigabyte
/// </summary>
/// <param name="bytes">Double -> Total bytes to be converted</param>
/// <param name="type">String -> Type of conversion to perform</param>
/// <returns>Int32 -> Converted bytes</returns>
/// <remarks></remarks>
public static double ConvertSize(double bytes, string type)
{
    try
    {
        const int CONVERSION_VALUE = 1024;
        //determine what conversion they want
        switch (type)
        {
            case "BY":
                 //convert to bytes (default)
                 return bytes;
                 break;
            case "KB":
                 //convert to kilobytes
                 return (bytes / CONVERSION_VALUE);
                 break;
            case "MB":
                 //convert to megabytes
                 return (bytes / CalculateSquare(CONVERSION_VALUE));
                 break;
            case "GB":
                 //convert to gigabytes
                 return (bytes / CalculateCube(CONVERSION_VALUE));
                 break;
            default:
                 //default
                 return bytes;
                 break;
          }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return 0;
      }
}

/// <summary>
/// Function to calculate the square of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be squared</param>
/// <returns>Double -> THe provided number squared</returns>
/// <remarks></remarks>
public static double CalculateSquare(Int32 number)
{
     return Math.Pow(number, 2);
}


/// <summary>
/// Function to calculate the cube of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be cubed</param>
/// <returns>Double -> THe provided number cubed</returns>
/// <remarks></remarks>
public static double CalculateCube(Int32 number)
{
     return Math.Pow(number, 3);
}

//Sample Useage
String Size = "File is " + ConvertSize(250222,"MB") + " Megabytes in size"

Solution 4

It depends on if you want the actual file size or the size on disk. The actual file size is the actual number of bytes that the file uses in memory. The size on disk is a function of the file size and the block size for your disk/file system.

Solution 5

I have a faint recollection that the answer on whether to use 1000 or 1024 lies in the casing of the prefix. Example: If the "scientific" 1000 scaling is used, then the "scientific" unit will be kB (just as in kg, kN etc). If the computer centric 1024 scaling is used, then the unit will be KB. So, uppercasing the scientific prefix makes it computer centric.

Share:
60,271

Related videos on Youtube

Mats
Author by

Mats

Updated on July 09, 2022

Comments

  • Mats
    Mats almost 2 years

    I'm using the DriveInfo class in my C# project to retrieve the available bytes on given drives. How to I correctly convert this number into Mega- or Gigabytes? Dividing by 1024 will not do the job I guess. The results always differ from those shown in the Windows-Explorer.

  • Russell Smith
    Russell Smith almost 15 years
    1024 is only "correct" in that it represents the actual number of bits on the disk. If you're concerned about correctness however, you need to display that with the unit "GiB". Using 1024 and calling it a "GB" is technically incorrect. GB is officially 1000 million, not 1024 million. I'd argue that 1000 is the correct usage from a human factors point of view. 1 gigawatts is 1000 megawatts. 1 GHz is 1000 MHz. By the same token (and for easier math by humans) 1000 gigabytes is 1000 megabytes.
  • Russell Smith
    Russell Smith almost 15 years
    while funny, it does not answer the question and may confuse those who are easily confused.
  • John Leidegren
    John Leidegren over 13 years
    No @Adam, @Bryan is correct. It doesn't make sense that the standard SI prefixes would mean different things when your talking about "drives" or "bytes", it's powers of 10, not powers of 2. e.g. When using powers of 2, the correct term would be mebibytes, not megabytes.
  • Adam Davis
    Adam Davis over 13 years
    @Bryan, @john - Users will complain if your program reports a different number than the OS and EVERY other program. If you want a reasonable user experience you should seriously consider sticking to the common convention. However, it's your program to do with as you please, and if you're ready to deal with customer questions regarding what a GiB is, or why your software reports different drive sizes than everything else they see, go for it. Keep in mind that the SI prefixes are great for technical documentation, but not necessarily designed for the end user to understand easily.
  • Jacob
    Jacob over 12 years
    KB = 1000 bytes, KiB = 1024 bytes
  • starblue
    starblue over 11 years
    +1 For k vs. K this is correct, but it doesn't help when the letter for the ISO prefix is already uppercase, as in M, G and T for Mega, Giga and Tera. And many people, especially from the US, have a tendency to mix up the case of ISO units and prefixes.
  • user2310967
    user2310967 over 10 years
    Apple software reports file size and drive storage as 1 GB = 1 billion bytes, and I think I've seen a few other programs do the same. The whole kilo- = 1024 thing arose at a time when saving a few bits on addressable space was a big deal and saving a couple of bit per variable dividing by 1024 was much computationally cheaper than dividing by 1000, but with modern hardware it hardly makes a difference. There's really not much to be gained from caring much about the difference, though. Do whatever makes you happy since some people are going to tell you you're wrong no matter what.
  • Zarepheth
    Zarepheth over 8 years
    Some machines have non-standard architectures with more or fewer bits per byte than 8. I'm thinking of the UNIVAC 1103/1103A/1105/1100/2200 mainframes with a 9-bits per byte (and the potential to run programs that only use 6-bits per byte). So the KBa would no longer by the Baker's Kilobyte on those machines, but the standard.