When learning about computer basics, we mentioned that negative numbers in computers are represented by supplementary codes, but why? Even after six yearsProgramClerk, I still don't know until I read the Harvard Open Class: Computer Science cs50. In layman's terms, the supplementary code is used because:
In the computer, the addition and subtraction are unified, so that (-5) + (5) can finally get 0.
For example, if we use 8 bits to represent numbers, (-5) and (+ 5) are represented:
Keys, 0101
1111,1011
We can use the method of adding a value to the computer to obtain (0000,). Here we use 8 bits to indicate numbers, so the highest bit of 1 is discarded, so we get 0.
Let's take a look at how the complement code is obtained. (-5) the complement code is obtained by adding 1 to the reverse code of (+ 5. This is also a reverse process, that is, the reverse result can be expressed as (1111,1111). If we add 1, we can get the representation of (decimal, 0000) (the highest bit is discarded ). To deepen our impression, let's take a look at (+ 5) + (-2). Their binary representation is:
Keys, 0101 => (+ 5)
1111,1110 => (-2)
The result of our binary addition is: (1, 0011,). If 1 of the highest bit is discarded, the result is exactly the binary representation of 3.