Two's Complement - MarekBykowski/readme GitHub Wiki

The problem: computers only have bits. How do you store -3?

How to read a pattern: if MSB = 0, it's just the positive value. If MSB = 1

Compute by hand

+3 = 0000 0011 → flip → 1111 1100 → +1 → 1111 1101 = -3
How to compute -x: flip all bits, add 1

+3  =  0000 0011
    →  1111 1100  (flip bits)
    →  1111 1101  (+1) = -3

-3 is stored as 2⁸ - 3. So -3 → 256 - 3 = 253, and 253 in binary is 1111 1101.

1    1    1    1    1    1    0    1
-128 + 64 + 32 + 16 + 8  + 4  + 0  + 1
64+32+16+8+4+1 = 125, and -128 + 125 = -3.
4-bit value 4-bit value
0111 +7 (MAX) 1000 -8 (MIN)
0001 +1 1111 -1
0000 0 1001 -7
// Trap: INT_MIN has no positive counterpart!
INT_MAX =  2147483647  =  0x7FFFFFFF
INT_MIN = -2147483648  =  0x80000000
abs(INT_MIN)  →  UB!  (result doesn't fit in int)