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.