View Single Post
Old 08-06-2006, 02:29 PM   #1 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 741
DJMaze is on a distinguished road
Thumbs up [TIP] Easy filesize to human readable

You ever wanted to have nice and clean filesize viewing?
I've seen many solutions but they are very bloated for just that simple task, hack I've even seen 72 lines of code in an article, that i still don't understand, on codeproject: http://www.codeproject.com/cpp/formatsize.asp

The trick is to know your <math.h>
WikiPedia properly describes which powers are used.

So how do we know in which range we are?
This is simple to understand if you've read the WikiPedia article.
KB = 1024
MB = 1024*1024
GB = 1024*1024*1024
TB.....

PHP Code:
#include <math.h>
#include <stdio.h>

// Bytes, Kilo, Mega, Giga, Tera, Peta, Exa, Zeta and Yotta
static const charhumanreadablebytes[] = {"B","KB","MB","GB","TB","PB","EB","ZB","YB"};

int main(void)
{
    
// the filesize to calculate
    
unsigned long filesize 22825;
    
// calculate the humanreadable bytes index
    
int i = (int) floorlog(filesize) / log(1024) );
    
// output the data
    
printf("filesize: %.02f %s\n"filesize/pow(1024i), humanreadablebytes[i]);
    return 
0;

output:
Code:
filesize: 22.29 KB
log Calculates the natural logarithm.
pow Calculates x to the power of y.

Basicly speaking "log() / log()" is the reversion of pow().
More information can be read here: http://en.wikipedia.org/wiki/Pow

You see? Only 4 lines of code to calculate a clean human readable output.

Want a rough estimated one that rounds up/down if the ammount is >= 1000?
PHP Code:
    // the filesize to calculate
    
unsigned long filesize 1062793248;
    
// calculate the humanreadable bytes index
    
int i = (int) floorlog(filesize) / log(1024) );
    
// Get a rougher size to prevent large outputs
    
if (filesize/pow(1024i) >= 1000) { ++i; }
    
// Prevent unknown format
    
if (8) { i=8; }
    
// output the data
    
printf_d("%.02f %s\n"filesize/pow(1024i), humanreadablebytes[i]); 
output:
Code:
filesize: 0.99 GB
Just my $0.02 to make your life easier.
__________________

UT: Ultra-kill... God like!
DJMaze is offline   Reply With Quote