๐2's complement
-x = ~x + 1 (invert bits, then add 1).
Last updated
Was this helpful?
-x = ~x + 1 (invert bits, then add 1).
Last updated
Was this helpful?
Was this helpful?
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โธ
โญ signed integer addition is a modular arithmetic.