Can someone explain me how this function works?
$size=100 //kb
if (filesize(file) > ($size << 10))
echo "file too big";
How does $size << 10
work? How can I make it use MB instead of KB?
The expression $size << 10
shifts the bit pattern to the left 10 times, effectively multiplying by 1024; In other words, it's $size * 1024
.
Every time you perform a left shift, you multiply the value by a factor of two. See also bitwise operators.
If you want $size
to mean size in MB, you multiply by another 1024, i.e.
if ($filesize($file) > $size * 1024 * 1024) {
echo "file too big";
}
Or:
if ($filesize($file) > $size << 20) {
echo "file too big";
}
Numbers are internally represented as binary, a series of zeroes and ones. The <<
operator will shift all the binary digits left by the specified amount of places, on the right it appends zeroes, example:
7 << 2
= 111 << 2 (7 = 111 in base two)
= 11100
= 28 (11100 = 28 in base ten)
The next you need to know that 1024 = 2
10
and therefore has a 10
digit binary representation, therefore shifting left by 10 digits results in the number being multiplied by 1024
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With