5

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.

Community
  • 1
  • 1
Jatinder
  • 732
  • 1
  • 6
  • 12

3 Answers3

5

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.

Bridge
  • 29,818
  • 9
  • 60
  • 82
Ashwin Prabhu
  • 9,285
  • 5
  • 49
  • 82
5

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
Blender
  • 289,723
  • 53
  • 439
  • 496
5

~ 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.
  • Then ~(-4) becomes 3.

Basically, ~n is equal to -n-1 for integers with Two's Complement representation.

Community
  • 1
  • 1
battery
  • 511
  • 2
  • 8