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

Mats picture Mats · Feb 19, 2009 · Viewed 57.2k times · Source

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.

Answer

Adam Davis picture Adam Davis · Feb 19, 2009

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.