Skip to content

Instantly share code, notes, and snippets.

@mlaily
Last active January 12, 2018 12:08
Show Gist options
  • Save mlaily/7662133 to your computer and use it in GitHub Desktop.
Save mlaily/7662133 to your computer and use it in GitHub Desktop.
Convert a length in bytes to a human readable string with the appropriate unit.
//we can't shift more than 63 bits with a long, so we would need a big int to support ZB and YB...
static readonly string[] units = new string[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB" };
/// <summary>
/// Supports any non negative value up to long.MaxValue (~8EB)
/// </summary>
public static string ToHumanReadableString(long length)
{
if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be negative!");
long shiftResult = 0;
long previousShiftResult = 0;
for (int i = 1; i < units.Length; i++)
{
shiftResult = 1L << (i * 10);
if (length < shiftResult || shiftResult == 64) // length < current unit value ? (or overflow, meaning we are in the EB range)
{
double value = ((double)length / previousShiftResult); //then we take the previous unit
string format = value < 1000 ? "{0:#0.0}{1}" : "{0:#0}{1}";
return string.Format(format, value, units[i - 1]);
}
previousShiftResult = shiftResult;
}
throw new ArgumentOutOfRangeException("length", "length is too big!"); //This is impossible
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment