2
$\begingroup$

x and y are 4 bit signed numbers (2s complement..)

x - y can be obtained by:

!(!x + y)

I know that in 2s complement

-y = (!y + 1)

So I can pretty much understand how this works:

x - y = x + (!y + 1)

But, what sort of magic is going on in here, how does this work:

!(!x + y)

I mean, when I do the math with pen and paper all is fine, but I do not know why it is working..

$\endgroup$
2
$\begingroup$

If $z$ is an $n$-bit number then $!z=2^n-1-z$. So $$ !(!x+y)=2^n-1-(2^n-1-x+y) = x-y. $$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.