确实.NET提供了一种简单的方法转换成字节,以KB,MB,GB等?转换成、字节、确实、简单

2023-09-02 21:10:26 作者:孤岛。

只是想知道,.NET提供了一个干净的方式来做到这一点:

just wondering if .net provides a clean way to do this:

int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
    y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
    y = string.Format("{0:n1} KB", x / 1024f);
}

等等...

etc...

推荐答案

下面是一个相当简洁的方式来做到这一点:

Here is a fairly concise way to do this:

static readonly string[] SizeSuffixes = 
                   { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value)
{
    if (value < 0) { return "-" + SizeSuffix(-value); } 
    if (value == 0) { return "0.0 bytes"; }

    int mag = (int)Math.Log(value, 1024);
    decimal adjustedSize = (decimal)value / (1L << (mag * 10));

    return string.Format("{0:n1} {1}", adjustedSize, SizeSuffixes[mag]);
}

和这里的原始实现我建议,这可能是稍微慢一些,但有点容易遵循:

And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:

static readonly string[] SizeSuffixes = 
                  { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value)
{
    if (value < 0) { return "-" + SizeSuffix(-value); } 

    int i = 0;
    decimal dValue = (decimal)value;
    while (Math.Round(dValue / 1024) >= 1)
    {
        dValue /= 1024;
        i++;
    }

    return string.Format("{0:n1} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));
 
精彩推荐