javascript - Why ~-(2 + "2") is 21? - Stack Overflow

I saw this question in a test, but I don't understand how operators work on the statement.let a =

I saw this question in a test, but I don't understand how operators work on the statement.

let a = ~-(2 + "2");
console.log(a);

I saw this question in a test, but I don't understand how operators work on the statement.

let a = ~-(2 + "2");
console.log(a);

Share Improve this question asked Feb 19, 2018 at 23:28 dev-ccdev-cc 4543 silver badges13 bronze badges 4
  • 1 Which part don't you understand? Break it down: 2 + "2" -> "22"; then -"22" -> -22; then ~-22 -> 21. Does this existing Q&A answer your question? If not, could you edit to be more specific about what it is? – jonrsharpe Commented Feb 19, 2018 at 23:30
  • 1 Did you try doing this a step at a time in the javascript console of your browser? Try 2 + "2" first, and so on... – lurker Commented Feb 19, 2018 at 23:31
  • simple answer, because type coercion, maths and bitwise operations - all these are documented - try mdn documentation for up to date documentation – Jaromanda X Commented Feb 19, 2018 at 23:34
  • 1 Check this out https://www.joezimjs./javascript/great-mystery-of-the-tilde/ – MaveRick Commented Feb 19, 2018 at 23:37
Add a ment  | 

2 Answers 2

Reset to default 10
~-(2 + "2")
  • 0: 2 + "2" (Concatenation) = "22"
  • 1: -"22" (Coercion) = -22
  • 2: ~-22 (Bitwise NOT) = -(-22 + 1) = 21

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

  • Step 1: (2+"2") results in the string "22"
  • Step 2: -("22") is the same as (-1)*("22"), and results in the number -22
  • Step 3: Bitwise not (~), which results in 21

To understand that last step, you need to know that JavaScript stores numbers as 64-bit floating point numbers, but all bitwise operations are performed on 32-bit signed integers using 2's pliment.

So:

  • -22 representation is the 2's pliment of +22
  • +22 in binary = 0000 0000 0000 0000 0000 0000 0001 0110
  • 2's pliment of (22) = (-22) = 1111 1111 1111 1111 1111 1111 1110 1001
    • 1 = 1111 1111 1111 1111 1111 1111 1110 1010
  • ~-22 = bitwise not of -22 = 0000 0000 0000 0000 0000 0000 0001 0101
  • 10101 in binary = 21 in decimal

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744067956a4553011.html

相关推荐

  • javascript - Why ~-(2 + "2") is 21? - Stack Overflow

    I saw this question in a test, but I don't understand how operators work on the statement.let a =

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信