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.
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.
1 Gigabyte is equal to 1,073,741,824 bytes = 230 bytes in binary.
1 Gigabyte is equal to 1000 megabytes (decimal). 1 GB = 103 MB in base 10 (SI). 1 Gigabyte is equal to 1024 megabytes (binary).
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]); }
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.
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.
Personally I'd write it like this: decimal GB = KB / (1024 * 1024);
but there's really no need to refactor the code as written.
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