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 char* humanreadablebytes[] = {"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) floor( log(filesize) / log(1024) );
// output the data
printf("filesize: %.02f %s\n", filesize/pow(1024, i), humanreadablebytes[i]);
return 0;
}
output:
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) floor( log(filesize) / log(1024) );
// Get a rougher size to prevent large outputs
if (filesize/pow(1024, i) >= 1000) { ++i; }
// Prevent unknown format
if (i > 8) { i=8; }
// output the data
printf_d("%.02f %s\n", filesize/pow(1024, i), humanreadablebytes[i]);
output:
Just my $0.02 to make your life easier.