Today I saw James Padolsey ‘s blog about the result of two consecutive bitwise non-operations equivalent to the floor.

Then skiyo blog did the next test, here is my code:

1
2
3
4
5
6
7
8
9
10
11
$time  =  microtime ( 1 ) ; 
for ( $i = 0 ; $i <= 100000 ; $i ++ )  { 
    ~~ 4.9 ; 
} 
echo  microtime ( 1 )  -  $time ; 
echo  "<br>" ; 
$time  =  microtime ( 1 ) ; 
for ( $i = 0 ; $i <= 100000 ; $i ++)  { 
    Floor ( 4.9 ) ; 
} 
echo  microtime, and ( . 1 )  -  $ Time ;

The result of this operation on my machine is

0.013797998428345
0.041538000106812

We can see that ~~ is almost three times faster than the floor.

But we need to know why ~~ is equivalent to the floor.

Here we need to involve a hex conversion and take a non-process.

Now we need a possible condition. Our variable is a signed integer 5.

We now give it a bitwise non-operation.

The binary of 5 is 0000 0101

Bitwise none after 1111 1010

At this time, the first sign bit 1 indicates a negative number. Negative numbers need to be inverted and +1.

The result of the other bit inversion is 000 0101 +1, and the result is 000 0110

Plus the previous symbol, it is -6.

At this time we gradually find a famous formula ~num = -(num + 1)

Go back to the above topic. If the above is not an integer and is a decimal 5.9?

Then the Zend engine will discard the binary part of the decimal part when calculating the fetch.

So ~5.9 will get -6.

Then do a bitwise non-. According to the above formula, we get 5.. This effect is the same as the floor().

What. You worry about using ~~ and leaving the floor will be a problem?

This answer is ok

For example, you can test with the following code

1
2
3
Echo ~~ 99999999999999.99 ; 
echo  "<br />" ; 
echo  floor ( 99999999999999.99 ) ;

The result of running on my computer is

276447231
99999999999999

We can see that it is overflowing with ~~.

So in a relatively small number of operations.. still use ~~ instead of the floor.

Be aware in JavaScript and PHP. The default variables can all be signed.

Leave a Reply