質問

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

$size << 10 means $size * pow(2, 10). Tenth power of 2 is 1024, which is number of bytes in a kilobyte. Number of bytes in a megabyte is pow(2, 20); you could write it as $size << 20.

The filesize function returns the size of the file in bytes. The $size value is defined as KB. ($size << 10) converts from KB to bytes so that the comparison is correct.

It's a left shift operator.

100 << 10 means shift 100 to the left by 10. That gives you 102400

It's the same as multiplying by 1024.

It's converting 100kb to bytes, which is what the filesize() returns.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top