Consider that the size units bytes, KB, MB, GB etc. are in successive powers of 1024, as in 1024^0, 1024^1, 1024^2 and so on.
So to know which unit to use for an arbitrary number of bytes, one needs to calculate the highest power of 1024 below it.
The integral part of a postive valued base 2 logarithm, ln2( bytes), is the power of two below it, so an easy way to obtain the power of 1024 below a number is to divide its base 2 logarithm by 10, since 1024 is 2^10, and take the integral part.
This yields a function
function p1024( n) { return Math.floor(Math.log2( n) / 10);}
to use as an index into the units abbreviation array.
The posted code is using mathematical knowledge that ln2( n) / 10
is equivalent to ln( n) / ln(1024)
, where ln
is the natural logarithm function and ln2
is a function for base 2 logarithms.
In Javascript Math
is a global object which is accessible to all javascript code. In Java you may need to import java.lang.Math
or java.lang.*
before use (not a Java expert here).