๐ŸŒŸ2's complement

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

JS โŸฉ statement โŸฉ expression โŸฉ operator โŸฉ arithmetic โŸฉ bitwise โŸฉ 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