๐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
num.toString(2) doesn't show 2's complement for negative integersโ
(-12).toString(2), // -1100 (what the โ)
(~~(-12)).toString(2), // -1100 (what the โ)
for n-bit signed integers,
-x
=~x + 1
.~x
=-x
- 1
.~(x
ยฑ M)
โก~x
(mod M), where M=2n~~(x
ยฑ M)
โก~~x
(mod M)โMโคx+y<M , where โ2Mโโคx,y<2Mโ (may overflow/underflow)
bitwise not (~) - inverts the bits.
double tilde (~~) - nearest integer towards 0.
replit๏ผ bitwise not (~)
// โญ test ~x
const M = 2 ** 32; // 4294967296
const m = M/8; // 536870912
// โญ overflow: 3m + 2m โก -3m (mod M)
~~(5*m), // -1610612736 (overflow)โ
-3*m, // -1610612736
// โญ underflow: -5m โก 3m (mod M)
~~(-5*m), // 1610612736 (underflow)โ
3*m, // 1610612736
-5*m, // -2684354560
// โญ ~(x ยฑ M) = ~x
~1234, // -1235
~(1234 - M), // -1235
~(1234 + M), // -1235
'----------',
// โญ `~x` === -x - 1 (truncate decimal if needed)
~(3), // -4 (-3 - 1)
~(-5), // 4 ( 5 - 1)
~(3.4), // -4 ( 3.4 -> 3 -> -3 - 1 = -4)
~(-5.5), // 4 (-5.5 -> -5 -> 5 - 1 = 4)
// โญ `~~x`:
~~(7.8), // 7 (โญ nearest integer towards 0)
~~(-3.4), // -3
~~(6), // 6 (โญ `~~x = x`, if x integer)
Bitwise NOT (~) - invert the bits.
Number.prototype.toString() - specify the radix.
Last updated