Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bytes to GB in C#?

Tags:

c#

refactoring

I was refactoring some old code and came across the following line of code to convert bytes to GB.

decimal GB = KB / 1024 / 1024 / 1024;

Is there a better way to refactor the following piece of code?

Update

I meant to say bytes to Gigabytes. I gave wrong information.

like image 403
Michael Kniskern Avatar asked Aug 07 '09 00:08

Michael Kniskern


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.

What is GB in binary?

1 Gigabyte is equal to 1,073,741,824 bytes = 230 bytes in binary.

What is the GB to MB conversion formula?

1 Gigabyte is equal to 1000 megabytes (decimal). 1 GB = 103 MB in base 10 (SI). 1 Gigabyte is equal to 1024 megabytes (binary).


4 Answers

I developed this method here, works up to TB.

private static string FormatBytes(long bytes) {     string[] Suffix = { "B", "KB", "MB", "GB", "TB" };     int i;     double dblSByte = bytes;     for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024)      {         dblSByte = bytes / 1024.0;     }      return String.Format("{0:0.##} {1}", dblSByte, Suffix[i]); } 
like image 142
JLopez Avatar answered Sep 19 '22 23:09

JLopez


If exact precision is not important, use double:

double gb = kb / 1048576D 

Agree with Pavel here - there's not really any need to refactor this code... in fact, if this is the biggest problem in your codebase, I think you might be sitting on the most well-written software ever.

like image 28
Rex M Avatar answered Sep 17 '22 23:09

Rex M


The original code is succinct, easy to read, and with reasonable variable names, self-documenting; I wouldn't change it.

If you absolutely must refactor, you could create a set of extension methods on the numeric types:

public static double BytesToKilobytes(this Int32 bytes)
{
    return bytes / 1024d;
}
public static double BytesToMegabytes(this Int32 bytes)
{
    return bytes / 1024d / 1024d;
}
public static double KilobytesToBytes(this double kilobytes)
{
    return kilobytes * 1024d;
}

//You can then do something like:
double filesize = 32.5d;
double bytes = filesize.KilobytesToBytes();

But unless your code does virtually nothing but convert bytes to kilobytes etc, all this will really do is clutter up Intellisense for no real gain.

like image 42
technophile Avatar answered Sep 21 '22 23:09

technophile


Personally I'd write it like this: decimal GB = KB / (1024 * 1024); but there's really no need to refactor the code as written.

like image 36
mattnewport Avatar answered Sep 19 '22 23:09

mattnewport