开发者

Displaying bandwidth speed in a user-friendly format

开发者 https://www.devze.com 2023-01-16 20:24 出处:网络
I\'m looking for a string conversion method that will receive an input of K开发者_JS百科B/s and converts it to the easiest readable format possible.

I'm looking for a string conversion method that will receive an input of K开发者_JS百科B/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


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


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消