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.
The simplest way to convert bytes to gigabytes is to divide the value of bytes by 1,000,000,000 and the result that you will get will be in the form of gigabytes.
Megabyte or MB One megabyte is about 1 million bytes (or about 1000 kilobytes).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With