Skip to content

Two's Complement

MarekBykowski edited this page May 26, 2026 · 1 revision
How to compute -x: flip all bits, add 1

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

Why it works: 2ⁿ - x  (complement to a power of two)
2⁴ - 3 = 13 = 1101
check: 0011 + 1101 = 10000 → carry discarded → 0000 ✓
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)

Clone this wiki locally