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.

"12344".ToBPSReadableFormat() outputs 12.3kbps

Quoting https://en.wikipedia.org/wiki/Metric_prefix for SI units; 
exaE 10181000000000000000000 quintillion
petaP 10151000000000000000 quadrillion
teraT 10121000000000000 trillion
gigaG 1091000000000 billion
megaM 1061000000 million
kilok 1031000 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 
https://metadataconsulting.blogspot.com/2020/06/CSharp-Get-a-number-or-integer-from-a-string-fast-a-speed-comparison.html


        /// <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);
        }

No comments:

Post a Comment