Converting Bytes to a Human Readable String in VBScript

This is a little function I like to call “ReadableBytes”. It is so named because I’d often call properties of an object and their values would be returned in bytes. Well this would be fine and dandy but it got hard to tell how big a particular file, folder, or drive was at a glance when it was listed as a series of 5 to 10 (or more) numbers. At first I was doing sloppy math to decode these values on a case by case basis, but got sick of if-thens and weird equations.

It occurred to me that the scale used to describe a large number of bytes were exactly a power larger than the scale before it. I wrote a formula to convert these values quite easily:

ScaledValue = Bytes / 1024 ^ Nth

Depending on what number you passed as “N” you’d get an appropriate scale (bytes, kilobytes, etc.)

Function ReadableBytes(num_bytes)
  'This function will convert a value passed in bytes to a more readable
  'format with the appropriate two character suffix. Ex:
  '       1936022345 would return 1.8 GB
  '       43112345 would return 41.12 MB
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  If num_bytes <= 1023 Then
    ReadableBytes = num_bytes & " B" 'Bytes!
  ElseIf num_bytes <= (1024 ^ 2) And num_bytes >= 1024 Then
    ReadableBytes = Round(num_bytes / 1024, 2) & " KB" 'Kilobytes!
  ElseIf num_bytes <= (1024 ^ 3) And num_bytes >= (1024 ^ 2) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 2), 2) & " MB" 'Megabytes!
  ElseIf num_bytes <= (1024 ^ 4) And num_bytes >= (1024 ^ 3) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 3), 2) & " GB" 'Gigabytes!
  ElseIf num_bytes <= (1024 ^ 5) And num_bytes >= (1024 ^ 4) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 4), 2) & " TB" 'Terabytes!
  ElseIf num_bytes <= (1024 ^ 6) And num_bytes >= (1024 ^ 5) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 5), 2) & " PB" 'Petabytes!
  ElseIf num_bytes <= (1024 ^ 7) And num_bytes >= (1024 ^ 6) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 6), 2) & " EB" 'Exabytes!
  ElseIf num_bytes <= (1024 ^ 8) And num_bytes >= (1024 ^ 7) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 7), 2) & " ZB" 'Zettabytes!
  ElseIf num_bytes <= (1024 ^ 9) And num_bytes >= (1024 ^ 8) Then
    ReadableBytes = Round(num_bytes / (1024 ^ 8), 2) & " YB" 'Yottabytes!
  End If
End Function

 

Leave a Comment