Why for two binary numbers $x,y$ is $\neg (\neg x + y) = x - y $ true?

210 Views Asked by At

Iv'e noticed, empirically, that for two integers $x$ and $y$ in binary representation (two's complement) it holds that $$\neg (\neg x + y) = x - y $$

Where $\neg$ is the bitwise "not" operation and we discard the overflow bit if it exists. (Say the two numbers are of a fixed width $k$ and so all operations are modulo $2^k$.)

Why does this work? (or am I wrong and there exists a counter example?)

1

There are 1 best solutions below

2
On BEST ANSWER

If you discard overflow, then for any $x$ you get $\neg x+x+1=11...11+00...01=00...00=0$, so $\neg x=-x-1$. Using only this identity, we can find \begin{align} \neg(\neg x+y) &=-(\neg x+y)-1 \\&=-(-x-1+y)-1 \\&=x-y. \end{align} For this reason, when your computer needs to calculate $-x$ from $x$, it actually calculates $\neg x+1$. Also, any expression of the form $x-y$ will likely be compiled into $x+\neg y+1$.

To sidetrack even more and relate this to some pure maths just for fun, recall $\sum_{n=1}^\infty x^n=(1-x)^{-1}$ holds for $|x|<1$. Now notice that plugging in $x=2$ the left hand side becomes $\sum_{n=1}^\infty2^n$ and the right hand side becomes $-1$. If you write down the partial sums of $\sum_{n=1}^\infty2^n$, you get $11...11$. This is not a coincidence :)