Search code examples
binaryprooftwos-complement

Explain why x == ~(~x + 1) + 1 (two's complement and back!)


As we all know usually negative numbers in memory represents as two's complement numbers like that

from x to ~x + 1

and to get back we don't do the obvious thing like

~([~x + 1] - 1)

but instead we do

~[~x + 1] + 1

can someone explain why does it always work? I think I can proof it with 1-bit, 2-bit, 3-bit numbers and then use Mathematical induction but it doesn't help me understand how exactly that works.

Thanks!


Solution

  • That's the same thing anyway. That is, ~x + 1 == ~(x - 1). But let's put that aside for now.

    f(x) = ~x + 1 is its own inverse. Proof:

    ~(~x + 1) + 1 =
    (definition of subtraction: a - b = ~(~a + b))
    x - 1 + 1 =
    (you know this step)
    x
    

    Also, ~x + 1 == ~(x - 1). Why? Well,

    ~(x - 1) =
    (definition of subtraction: a - b = ~(~a + b))
    ~(~(~x + 1)) =
    (remove double negation)
    ~x + 1
    

    And that (slightly unusual) definition of subtraction, a - b = ~(~a + b)?

    ~(~a + b) =
    (use definition of two's complement, ~x = -x - 1)
    -(~a + b) - 1 =
    (move the 1)
    -(~a + b + 1) =
    (use definition of two's complement, ~x = -x - 1)
    -(-a + b) =
    (you know this step)
    a - b