现在的位置: 首页 > 综合 > 正文

.NET(C#):将数据字节大小转换成易读的单位字符串

2012年01月10日 ⁄ 综合 ⁄ 共 1703字 ⁄ 字号 评论关闭

计算机中数据大小一般以字节为单位,数据类型通常是long类型,转换成易读的单位字符串,比如1024字节就显示1KB。1024*1024字节则显示1MB……

 

Google中搜索了半天,在StackOverflow中找到一个好的答案:

http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java

 

不过是用Java写的,把他改成C#:

public static String humanReadableByteCount(long bytes, bool si)

{

    int unit = si ? 1000 : 1024;

    if (bytes < unit) return bytes + " B";

    int exp = (int)(Math.Log(bytes) / Math.Log(unit));

    String pre = (si ? "kMGTPE" : "KMGTPE")[exp - 1] + (si ? "" : "i");

    return String.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), pre);

}

si参数为True则是以国际单位制1000为单位,为False则是以二进制的1024为单位进位。

 

测试代码(测试数据和原页面上的一样):

long[] longs = { 0, 27, 999, 1000, 1023, 1024, 1728, 110592, 7077888, 452984832, 28991029248, 1855425871872, long.MaxValue };

foreach (var l in longs)

    Console.WriteLine("{0,-20} {1,-10} {2,-10}", l, humanReadableByteCount(l, true), humanReadableByteCount(l, false));

 

输出:

0                    0 B        0 B

27                   27 B       27 B

999                  999 B      999 B

1000                 1.0 kB     1000 B

1023                 1.0 kB     1023 B

1024                 1.0 kB     1.0 KiB

1728                 1.7 kB     1.7 KiB

110592               110.6 kB   108.0 KiB

7077888              7.1 MB     6.8 MiB

452984832            453.0 MB   432.0 MiB

28991029248          29.0 GB    27.0 GiB

1855425871872        1.9 TB     1.7 TiB

9223372036854775807  9.2 EB     8.0 EiB

 

不过通常情况下,我们都会使用1024单位进位而不是1000,这样可以更精确地显示大小,同时单位上也不加i符号(代表它不是1000进位的单位)。所以我把它做了些小修改:

//修改自

//http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java

public static string humanReadableByteCount(long bytes)

{

    int unit = 1024;

    if (bytes < unit) return bytes + " B";

    int exp = (int)(Math.Log(bytes) / Math.Log(unit));

    return String.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), "KMGTPE"[exp - 1]);

}

抱歉!评论已关闭.