Shane Tomlinson - 1 year ago 101

Javascript Question

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would give back the same value, wouldn't it?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number.

In other words, it yields:

```
function(x) {
if(x < 0) return Math.ceil(x);
else return Math.floor(x);
}
```

only if *x* is between -(2^{31}) and 2^{31} - 1. Otherwise, overflow will occur and the number will "wrap around".

This may be considered useful to convert a function's string argument to a number, but both because of the possibility of overflow and that it is incorrect for use with non-integers, I would not use it that way except for "code golf" (*i.e.* pointlessly trimming bytes off the source code of your program at the expense of readability and robustness). I would use `+x`

or `Number(x)`

instead.

The number -43.2, for example is:

-43.2_{10}= 11111111111111111111111111010101_{2}

as a signed (two's complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:

NOT -43_{10}= 00000000000000000000000000101010_{2}= 42_{10}

Inverting again gives:

NOT 42_{10}= 11111111111111111111111111010101_{2}= -43_{10}

This differs from `Math.floor(-43.2)`

in that negative numbers are rounded toward zero, not away from it. (The floor function, which would equal -44, always rounds down to the next lower integer, regardless of whether the number is positive or negative.)