Possible Duplicate:
Understanding javascript bitwise NOT
I found it here: front-end-interview-questions question down below. what this code ~~3.14 will return?
I searched on google but didn't found anything on this.
Possible Duplicate:
Understanding javascript bitwise NOT
I found it here: front-end-interview-questions question down below. what this code ~~3.14 will return?
I searched on google but didn't found anything on this.
It will return 3. ~
represents bitwise NOT operator in JavaScript.
Basically ~3.14 is same as ~3, which is ~011 in binary => 100 or 4 in base 10. ~4 or ~100 is 011 or 3 in base 10.
The tilde performs a bitwise NOT on the input after converting it to a 32-bit integer.
From the MDN:
Bitwise NOTing any number
x
yields-(x + 1)
. For example,~5
yields-6
.
In your case:
~~3.14
= -((~3.14) + 1)
= -(-(3.14 + 1) + 1)
= -(-(3 + 1) + 1)
= -(-4 + 1)
= -(-3)
= 3
~
is the bitwise complement operator in JavaScript (and C/C++ and other languages).
You can find more details here: How does the bitwise complement (~) operator work?
In this case:
3.14
is converted from floating point to integer, so it becomes 3
.~3
is -4
because of the Two's Complement representation.~(-4)
becomes 3
.Basically, ~n
is equal to -n-1
for integers with Two's Complement representation.