Sunday, December 19, 2010

FormatBytes() - How big is that?

A handy function for formatting bytes, such as disk or file sizes.

1,024 bytes = 1 KB
1,048,576 bytes = 1 MB
1,073,741,824 bytes = 1 GB
1,099,511,627,776 bytes = 1 TB
1,125,899,906,842,620 bytes = 1 PB
1,152,921,504,606,850,000 bytes = 1 EB
1,180,591,620,717,410,000,000 bytes = 1 ZB

Kilobyte
Megabyte
Gigabyte
Terabyte
Petabyte
Exabyte
Zetabyte

To format a byte count as a string, here’s a quick little routine to do the trick.

   1:      Public Function FormatBytes(ByVal nBytes As Double, Optional ByVal szFormatString As String = "###,###,###,##0") As String
   2:   
   3:          Dim POSTFIXES() As String = {"Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
   4:          For n As Integer = POSTFIXES.Length - 1 To 0 Step -1
   5:              Dim nPow As Double = Math.Pow(1024, n)
   6:              If nBytes >= nPow Then
   7:                  nBytes /= nPow
   8:                  Return nBytes.ToString(szFormatString) & " " & POSTFIXES(n)
   9:              End If
  10:          Next
  11:          Return nBytes.ToString(szFormatString) & " Bytes"
  12:   
  13:      End Function

No comments: