Re: Converting bytes

new topic     » goto parent     » topic index » view thread      » older message » newer message

Here's the method I've been using for like, ever... smile

Units are expressed as either powers of 1000 (SI unit notation) or powers of 1024 Binary prefix notation) which makes this a very simple math problem.

  1. Create a list of suffixes in their ascending order.
  2. Divide the size value down by 1000 (or 1024) until it's less than 1000 (or 1024).
  3. Each time the size is divided, increment the index counter (moving the suffix up one level).
  4. Adjust the suffix to include "B" (for 1000) or "iB" (for 1024).
  5. Format the number and tack the suffix on the end.

include std/console.e 
include std/utils.e 
 
-- format types 
constant FORMAT_SI = 1000 
constant FORMAT_BN = 1024 
 
-- format suffixes 
constant SUFFIX = {"bytes","K","M","G","T","P","E","Z","Y"} 
 
function format_size( atom size, integer ftype = FORMAT_BN ) 
     
    integer index = 1 
    while size >= ftype do -- ftype is 1000 or 1024 
        size /= ftype 
        index += 1 
    end while 
     
    sequence suffix = SUFFIX[index] 
    if index > 1 then 
        suffix &= iff( ftype = FORMAT_BN, "iB", "B" ) 
    end if 
     
    return sprintf( "%.3g %s", {size,suffix} ) 
end function 
 
procedure test( atom size ) 
     
    sequence str1 = format_size( size, FORMAT_SI ) 
    sequence str2 = format_size( size, FORMAT_BN ) 
     
    printf( 1, "%10d %10s %10s\n", {size,str1,str2} ) 
     
end procedure 
 
procedure main() 
     
    ------------------  -- | SI units | Binary    | 
    test(          0 )  -- |  0 bytes |   0 bytes | 
    test(      10000 )  -- |    10 KB |  9.77 KiB | 
    test(      65536 )  -- |  65.5 KB |    64 KiB | 
    test(   10000000 )  -- |    10 MB |  9.54 MiB | 
    test(   16777216 )  -- |  16.8 MB |    16 MiB | 
    test( 1000000000 )  -- |     1 GB |   954 MiB | 
    test( 1073741824 )  -- |  1.07 GB |     1 GiB | 
     
    maybe_any_key() 
     
end procedure 
 
main() 

-Greg

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu