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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
only if x is between -(231) and 231 – 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
+xorNumber(x)instead.How this is the NOT of the NOT
The number -43.2, for example is:
as a signed (two’s complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:
Inverting again gives:
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.)