In order to represent a negative integer in a computer, some encoding methods are added with a symbol bit to distinguish between a positive integer and a negative integer.
However, the addition and subtraction of integers becomes more complex.
In fact, an integer is a whole. It seems unnecessary to use a signed bit to distinguish between a positive integer and a negative integer.
The idea of complement code may be like this-complement Code can be considered as a encoding method. In this encoding method, it is natural that the expression of a positive integer is the same as the number of unsigned integers, but what about negative numbers?
In order to simplify the addition and subtraction operations of this encoding method, you can consider converting the subtraction x-y of integers into addition x + (-y) and performing all addition and subtraction operations by using a calculator, the negative number encoding method is provided here-if this calculation method is feasible, there will be x + (-x) = 0, that is, a positive number can be used to define a negative number.
Assume that the 4-bit binary code is used for encoding. Because 0010 + 1110 = 0000, the encoding of-2 is 1110. Similarly, we can encode the remaining negative numbers.
Sort out the code (8-bits) in this way ).
1) The positive integer and the unsigned number are encoded in the same way (0 ~ 2 ^ 7-1)
2) use 0 and a positive integer (1 ~ 2 ^ 7) to define the negative integer encoding, so that x + (-x) = 0
As can be seen from the definition of negative integers, the encoding of negative numbers is unique, and the value ranges from 2 to 7 ~ Between 2 ^ 8.
If the value of x is reversed by 1 and the value of Add yourself, the result is 0. X is unique and defined by a negative integer. the encoding of a negative integer must exist. Therefore, x is encoded as a negative integer.
It can be proved that the addition and subtraction operations of this encoding can be implemented using a calculator.
Assume there are two integers x and y (the calculation result is not overflow ).
1) x + y = x + y to get the correct result
2) x + (-y), classification Discussion
A) if x> y, from 1), you can make x = y + (x-y), SO x + (-y) = (y + (x-y )) + (-y) = (y + (-y) + (x-y) = (x-y). The correct result is displayed.
B) If x <y, a) can make x = y + (-(y-x), then x + (-y) = (y + (-(y-x) + (-y) = (y + (-y) + (-(y-x )) = (-(y-x) to get the correct result.
3) (-x) + (-y), by B) can make (-x) = y + (-(x + y), so (-x) + (-y) = (y + (-(x + y) + (-y) = (y + (-y )) + (-(x + y) = (-(x + y). The correct result is displayed.