How does ~~ math.floor work?

I understand that ~ is a bitwise NOT operator, but how to invert bits by a number two times makes it a Math.floor function. What does ~~ ("double tilde") do in Javascript? describes the differences between using Math.floor and bitwise operations for round numbers in Javascript, but I'm wondering how exactly this performs bit drilling.

thank

+4
source share
3 answers

From specification , Bitwise NOT,~

  • Let it exprbe the result of computing UnaryExpression.
  • Let oldValuebe ToInt32(GetValue(expr)).
  • oldValue. 32- .

ToInt32 .

"" 32- i i XOR 0xFFFFFFFF.

, , ~~i

ToInt32(i) XOR 0xFFFFFFFF XOR 0xFFFFFFFF
// same as 
ToInt32(i) XOR 0x00000000
// same as
ToInt32(i) 

.


x | 0 ~~x, .

+2

~ . , , Javascript . , Javascript , , , .

So ~x castToInt(x). , castToInt(x).

, integer Math.floor. , , Math.floor . :

js> ~~(-4.5)
-4
js> Math.floor(-4.5)
-5
js> ~~Infinity
0
js> Math.floor(Infinity)
Infinity
js> ~~NaN
0
js> Math.floor(NaN)
NaN
js> Math.floor(1e12)
1000000000000
js> ~~1e12 
-727379968      // <- be aware of integer overflows!
+5

This is essentially the equivalent of a truncation function (in the sense that it distinguishes a float from an integer, which does just that), which JavaScript does not have. That is why for negative numbers the behavior is really closer to Math.ceil.

+1
source

Source: https://habr.com/ru/post/1530787/


All Articles