## Wednesday, May 20, 2020

### CSharp - Human readable video bit rate (bits per second) format

Format video bit rate measured in bits per second into "human readable" format, meaning that number is formatted as specified by metric SI convention using E,P,T,G,M,k prefix units.

Quoting https://en.wikipedia.org/wiki/Metric_prefix for SI units;
 exa E 1018 1000000000000000000 quintillion peta P 1015 1000000000000000 quadrillion tera T 1012 1000000000000 trillion giga G 109 1000000000 billion mega M 106 1000000 million kilo k 103 1000 thousand
This string extension method will format to bps to 1 decimal place.

Update June 1, 2020:  You can combine this with fast integer extraction

```        /// <summary>
/// Return bits per second formatted w/ metric SI units & to 1 decimal place - https://en.wikipedia.org/wiki/Metric_prefix
/// </summary>
/// <param name="numlong"></param>
/// <returns></returns>
public static string ToBPSReadableFormat(this string numlong)
{
string unit;
double d;

long l = 0; //reqr'd -> cannot do a bitwise shift on a double
long.TryParse(numlong, out l);

if (l==0) return "0bps";

long abs = (l < 0 ? -l : l);   //absolute value, we could use ulong if you know you will not get negative values

if (abs >= 0x1000000000000000) // Exabyte
{
unit = "Ebps";
d = (l >> 50);
d = (d / 1000);
}
else if (abs >= 0x4000000000000) // Petabyte
{
unit = "Pbps";
d = (l >> 40);
d = (d / 1000); // Divide by 1000 to get fractional value
}
else if (abs >= 0x10000000000) // Terabyte
{
unit = "Tbps";
d = (l >> 30);
d = (d / 1000);
}
else if (abs >= 0x40000000) // Gigabyte
{
unit = "Gbps";
d = (l >> 20);
d = (d / 1000);
}
else if (abs >= 0x100000) // Megabyte
{
unit = "Mbps";
d = (l >> 10);
d = (d / 1000);
}
else if (abs >= 0x400) // Kilobyte
{
unit = "kbps";
d = l;
d = (d / 1000);
}
else
{
unit = "bps";
d = l;
}

return string.Concat(d.ToString("0.#"),unit);
}
```