How does the bitwise complement operator (~ tilde) work?

后端 未结 15 1426
无人共我
无人共我 2020-11-22 07:46

Why is it that ~2 is equal to -3? How does ~ operator work?

15条回答
  •  囚心锁ツ
    2020-11-22 08:05

    Javascript tilde (~) coerces a given value to the one's complement--all bits are inverted. That's all tilde does. It's not sign opinionated. It neither adds nor subtracts any quantity.

    0 -> 1
    1 -> 0
    ...in every bit position [0...integer nbr of bits - 1]
    

    On standard desktop processors using high-level languages like JavaScript, BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.

    JavaScript Tilde operation (1's complement)
    
    BASE2 lens
    ~0001 -> 1110  - end result of ~ bitwise operation
    
    BASE10 Signed lens (typical JS implementation)
    ~1  -> -2 
    
    BASE10 Unsigned lens 
    ~1  -> 14 
    

    All of the above are true at the same time.

提交回复
热议问题