๐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
โญ signed integer addition is a modular arithmetic.
Last updated
Was this helpful?