Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 617
Mats Avatar asked Feb 19 '09 15:02

Mats


People also ask

How do you convert bytes to gigabytes?

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.

How many bytes is a mega gigabyte?

Megabyte or MB One megabyte is about 1 million bytes (or about 1000 kilobytes).


1 Answers

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.

like image 73
Adam Davis Avatar answered Sep 19 '22 18:09

Adam Davis