I was trying to convert file size from bytes to human understandable value and found one interesting solution. I will provide it on php with explanation.
function bytesConvert($size) {
$base = log($size)/log(1024);
$suffix = array('', 'Kb', 'Mb', 'Gb', 'Tb');
return round(pow(1024, $base - floor($base)), 2) . $suffix[floor($base)];
}
Where:
- log - Natural logarithm;
- round - Rounds a float with specified precision;
- pow - Exponential expression; Returns base raised to the power of exp;
- floor - Round fractions down;
I use this solution and it works. But it's like Cargo cult for me. I understand every single action at this function but can't get a clue why it works. I will be very grateful if somebody will explain it.
In points:
So, by separating the integral and fractional part of $\log_{1000}n$ you know how many triples of zeros you should append...
{'', 'K', 'M', 'G', 'T'}[$\lfloor\log_{1000}42)\rfloor$] == ' '{'', 'K', 'M', 'G', 'T'}[$\lfloor\log_{1000}1234\rfloor$] == 'K'{'', 'K', 'M', 'G', 'T'}[$\lfloor\log_{1000}7654321\rfloor$] == 'M'{'', 'K', 'M', 'G', 'T'}[$\lfloor\log_{1000}123456789\rfloor$] == 'G'...and what should be the prefix:
This all works for any base like 10, 16, 1000, 1024, whatever, and so your algorithm follows ;-)
I'm sorry if the explanation came too basic for you, but I didn't know your background; I hope it will help ;-)