About to read computer science, I have just stumbled accross the concept of "Two's complement". I understand how to apply the "algorithm" to calculate these on paper, but I have not yet obtained an understanding of why it works. I think this site: https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html provides an explanaition why "flipping the digits" and adding one produces the compliment. What I do not understand is why adding the complement is equivalent to substracting the original number. Could somebody please give an explanation (maybe with a decimal example of the same concept as well?)?

Many thanks!

----------------------------------------------------------------------------

I'll stick to 8-bit quantities, but the same applies in general.

The key to understanding two's complement is to note that we have a set of finitely many (in particular, 28=256.


Intuitively, arithmetic modulo 12.

For example, if it is 2:00, since

11+3=14≡2(mod12)

and similarly, if it is 9 since

1−4=−3≡9(mod12)

Notice that subtracting 12−4=8 hours. In particular, we could have computed the above as follows:

1−4≡1+8=9(mod12)

That is: when performing arithmetic modulo n−x.

 


Now, let's apply this idea modulo 00000011 is the same as adding

100000000⏞8−00000011=1+11111111⏞8−00000011=1111101

and there's your two's complement.

 

Notably, we don't think of 128.


Note: an interesting infinite analog to the two's complement system of subtraction is that of infinite series 2-adic numbers. In particular, we can say something strange like

1

相关文章: