javascript - Why :Math.floor(2e+21) != ~~(2e+21) -


I am not an expert in bitwise operators, but I often see a pattern which is used by the programmers of 256k demos in competitions. Instead of using the Math.floor () function, the double bitwait operator is used ~~ (maybe faster?).

Like this:

  Math.flur (2.1); // 2 ~~ 2.1 // 2  

The search has shown that there are more patterns in the same way:

  2.1 | 0 // 2 2.1 & gt; & Gt; 0/2>  

When it plays in Dev Console, I have seen a behavior which I am not completely convinced.

  Math flooring (2E + 21); // 2e + 21 ~~ 2e + 21; // -1119879168 2e + 21 | 0; // -1119879168  

What's going on under the hood?

Felix King reported that the number is being converted to 32 bit signed entries. 2e9 is less than the maximum positive value of a signed int, so it works:

  ~~ (2e 9) // 2000000000  

But when You can not use all bits till 2e10, so it only takes the lowest 32 bits and it changes to an integer:

  ~~ (2e10) // - 1474836480  

You can confirm it using another bitware operator and it is receiving the lowest 32 bits:

  2e10 & amp; 0xFFFFFFFF // also -1474836480 ~~ (2e10 and 0xFFFFFFF) // also -1474836480  

Mutate Flu is created for large numbers, so if the accuracy is important above a large range So you should use it.

Also note: ~~ Transaction is that which is similar to floating only positive numbers, it will not work for negative:

  math.flur ( -2.1) // -3 ~~ (-2.1) // -2  

Comments