Created
October 8, 2020 10:58
-
-
Save Rudde/a72b8d26f3de84141da8699c9b27ab26 to your computer and use it in GitHub Desktop.
Will convert bytes into readable data units.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Globalization; | |
namespace HumanReadable | |
{ | |
public class HumanReadableBytes | |
{ | |
private readonly Dictionary<Base, Unit[]> _baseUnits = new Dictionary<Base, Unit[]>(); | |
public int DecimalPoints = 2; | |
public int DecimalsAfterPower = 2; | |
public string DecimalSeparator = null; | |
public string ThousandSeparator = null; | |
public HumanReadableBytes() | |
{ | |
Init(); | |
} | |
private void Init() | |
{ | |
_baseUnits.Add(Base.Base10, new Unit[] | |
{ | |
new Unit("byte", "B"), | |
new Unit("kilobyte", "kB"), | |
new Unit("megabyte", "MB"), | |
new Unit("gigabyte", "GB"), | |
new Unit("terrabyte", "TB"), | |
new Unit("petabyte", "PB") | |
}); | |
_baseUnits.Add(Base.Base2, new Unit[] | |
{ | |
new Unit("byte", "B"), | |
new Unit("kibibyte", "KiB"), | |
new Unit("mebibyte", "MiB"), | |
new Unit("gibibyte", "GiB"), | |
new Unit("tebibyte", "TiB"), | |
new Unit("pebibyte", "PiB") | |
}); | |
} | |
public string GenerateHumanReadableString(long bytes, Base baseUnit = Base.Base10, bool longName = false) | |
{ | |
NumberFormatInfo nfi = GetNumberFormatInfo(); | |
decimal decimalSize = bytes; | |
int loop = 0; | |
while (decimalSize >= (int)baseUnit && _baseUnits[baseUnit].Length - 1 > loop) | |
{ | |
decimalSize /= (int)baseUnit; | |
loop++; | |
} | |
string format; | |
if (loop >= DecimalsAfterPower) | |
{ | |
format = $"#,0.{new string('0', DecimalPoints)}"; | |
} | |
else | |
{ | |
format = "#,0"; | |
} | |
var unit = longName ? _baseUnits[baseUnit][loop].LongName : _baseUnits[baseUnit][loop].ShortName; | |
string formatedNumber = decimalSize.ToString(format, nfi); | |
return $"{formatedNumber} {unit}"; | |
} | |
private NumberFormatInfo GetNumberFormatInfo() | |
{ | |
NumberFormatInfo nfi = new NumberFormatInfo(); | |
nfi.NumberDecimalSeparator = | |
DecimalSeparator ?? CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; | |
nfi.NumberGroupSeparator = | |
ThousandSeparator ?? CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; | |
return nfi; | |
} | |
public enum Base | |
{ | |
Base10 = 1000, | |
Base2 = 1024 | |
} | |
private readonly struct Unit | |
{ | |
public Unit(string longName, string shortName) | |
{ | |
this.LongName = longName; | |
this.ShortName = shortName; | |
} | |
public readonly string LongName; | |
public readonly string ShortName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment