Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise Operators file function php

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?

like image 475
Alberto Alibaba Avatar asked Dec 20 '22 18:12

Alberto Alibaba


2 Answers

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";
}
like image 113
Ja͢ck Avatar answered Jan 02 '23 08:01

Ja͢ck


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 = 210 and therefore has a 10 digit binary representation, therefore shifting left by 10 digits results in the number being multiplied by 1024.

like image 35
TimWolla Avatar answered Jan 02 '23 10:01

TimWolla