Re: Converting bytes

new topic     » goto parent     » topic index » view thread      » older message » newer message
ghaberek said...

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

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

Thank you very much Greg,

I would love to try you code.

But right now I only have Euphoria 3.1 working.

I'm having problems with 4.1.

Could you repost your code in the 3.1 form?

Don Cole

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

Search



Quick Links

User menu

Not signed in.

Misc Menu