.NET(C#):將資料位元組大小轉換成易讀的單位字串

來源:互聯網
上載者:User

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

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.