🌟2's complement

-x = ~x + 1 (invert bits, then add 1).

JSstatementexpressionoperatorarithmeticbitwise ⟩ 2's complement

(inverts the bits, then add 1)

in signed integer addition, -x (the 2's complement of x) is defined to be ~x + 1.

// (for simplicity, 8-bit signed integer)
//
// ┌─ (⭐️ sign bit: 0 nonnegative, 1 negative)
   0110 1010    //  x
+  1001 0101    // ~x (⭐️ invert the bits)
------------
   1111 1111    // x + (~x) = 1111 1111 = M - 1, where M = 2⁸
+          1    // +1 (⭐️ add 1)
------------    // 
  10000 0000    // x + (~x + 1) ≡ 0 (mod M)
                //     ╰─ -x ─╯ <---- 🔸 define -x = ~x + 1
                //
                // 🔸 Definition: -x = ~x + 1 (2's complement)
                // ⭐️ this is why ~x = -x - 1 
💡 proof: ~(x ± M) ≡ ~x , ~~(x ± M) ≡ ~~x (mod M)
// 1. ~(x ± M)  ≡  ~x
// proof:
~(x ± M) = -(x ± M) - 1        // definition
         = -x ± M -1
-x - 1 (mod M)      // modular arithmetic
         = ~x                  // definition
// 2. ~~(x ± M)  ≡  ~~x
// proof:
~~(x ± M) = ~(~(x ± M))        // `~` is right-to-left associative
~(~x)              // by proof 1.
          = ~~x                // `~` is right-to-left associative

signed integer addition is a modular arithmetic.

Last updated