LostS has asked for the wisdom of the Perl Monks concerning the following question:

Hey Everyone,

Here is what I am doing... I am grabbing the file size via -s HOWEVER... that is in Bytes... Is there some way to convert this from Unix Bytes to kb?? So a 82591 byte file will be 83k (You know round up)...

Thanks,
Billy S.

Replies are listed 'Best First'.
Re: File Size Conversion
by davorg (Chancellor) on Aug 14, 2001 at 18:51 UTC
      That works wonderfully :) Thank you sooo much :)
Re: File Size Conversion
by dragonchild (Archbishop) on Aug 14, 2001 at 18:47 UTC
    There are 1024 bytes in a kb. There are 1024 kb in a mb, and so on.

    So, if you want to convert 82591 bytes to kb, you divide by 1024. If you want to convert the result to an integer number, you can use int or sprintf.

    ------
    /me wants to be the brightest bulb in the chandelier!

    Vote paco for President!

(elbie): File Size Conversion
by elbie (Curate) on Aug 14, 2001 at 20:18 UTC
    If you find this useful, please feel free to use it. I can't remember where I grabbed the download time calculation from. I think I just went looking for large files on download.com. :)

    my $size = ( stat "$filename" )[7]; my $sizeunit = "b"; my $dltime = $size / 430080; if( $dltime < 1.0 ) { $dltime = "less than 1"; } else { $dltime = sprintf "%.0f", $dltime; } $dltime .= " min"; if( $size > 1024.0 ) { $sizeunit = 'Kb'; $size /= 1024.0; } if( $size > 1024.0 ) { $sizeunit = 'Mb'; $size /= 1024.0; } $size = sprintf( "%.1f %s", $size, $sizeunit );

    elbieelbieelbie

Re: File Size Conversion
by dga (Hermit) on Aug 14, 2001 at 22:41 UTC

    If you want nice printed output rounded then the printf "%.0f" deal is a very tidy way to go.

    If you are trying to figure allocation blocks, you need to always round up and use the allocation size of where you are going.

    For example, I did a program to split up multiple files to put on floppies and so that looked something like.

    my $size=-s _; my $blocks=int($size/512)+1;

    Floppy blocks were 512 bytes and there were 2880 of them on a disk less the formatting.

    Also could add a check for a file exactly a multiple of 512 for which this code will reserve an extra block.