Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying bandwidth speed in a user-friendly format

I'm looking for a string conversion method that will receive an input of KB/s and converts it to the easiest readable format possible.

e.g. 1500 b/s = 1.46 Kb/s
e.g. 1500 Kb/s = 1.46 Mb/s
e.g. 1500 Mb/s = 1.46 Gb/s

Thanks

like image 700
Peter Avatar asked Sep 20 '25 05:09

Peter


2 Answers

Try this:

var ordinals = new [] {"","K","M","G","T","P","E"};

long bandwidth = GetTheBandwidthInBitsPerSec();

decimal rate = (decimal)bandwidth;

var ordinal = 0;

while(rate > 1024)
{
   rate /= 1024;
   ordinal++;
}

output.Write(String.Format("Bandwidth: {0} {1}b/s", 
   Math.Round(rate, 2, MidpointRounding.AwayFromZero), 
   ordinals[ordinal]));

The ordinals (prefixes) available here are Kilo-, Mega-, Giga-, Tera-, Peta-, Exa-. If you really think your program will be around long enough to see Zettabit and Yottabit network bandwidths, by all means throw the Z and Y prefix initials into the array.

To convert from one formatted string to the other, split on spaces, look at the term that will be the number, and then search the term immediately following for one of the prefixes. Find the index of the ordinal in the array, add 1, and multiply by 1024 that many times to get to bits per second:

var bwString= GetBandwidthAsFormattedString(); //returns "Bandwidth: 1056 Kb/s";

var parts = String.Split(bwString, " ");
var number = decimal.Parse(parts[1]);
var ordinalChar = parts[2].First().ToString();
ordinalChar = ordinalChar = "b" ? "" : ordinalChar;

var ordinal = ordinals.IndexOf(ordinalChar)

... //previous code, substituting the definition of ordinal
like image 163
KeithS Avatar answered Sep 22 '25 17:09

KeithS


I made this code in about 30 secondes, so there is no validation, but I think it does what you want

        string vInput = "1500 Kb/s";
        string[] tSize = new string[] { "b/s", "Kb/s", "Mb/s", "Gb/s" };
        string[] tSplit = vInput.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
        double vSpeed = Double.Parse(tSplit[0]) / 1024.0;
        vSpeed = Math.Round(vSpeed, 2);
        int i = 0;
        for(i = 0; i < tSize.Length;++i)
        {
            if(tSplit[1].StartsWith(tSize[i]))
            {
                break;
            }
        }
        string vOutput = vSpeed.ToString() + " " + tSize[i+1];
like image 44
Wildhorn Avatar answered Sep 22 '25 19:09

Wildhorn