電腦中資料大小一般以位元組為單位,資料類型通常是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]);
}