Have to know the knowledge of complement

Whatever the programming language, the code will eventually be compiled and interpreted into binary data that a computer can read and run.

In binary data, numbers can be divided into source code, complement code and inverse code.

notation

Source code: The value is preceded by a sign bit

For example, the binary representation of 10 and -10 is as follows:

The source code of # 10 is 0000 1010Copy the code

The highest bit represents the sign bit, 0 represents a positive number, and 1 represents a negative number.

Reverse code: on the basis of the original code, the symbol bit is unchanged, and the rest bits are reversed

Continue with -10 on the top side:

The inverse of # -10 is 1111 0101Copy the code

Complement: The complement of a negative number is the inverse plus 1, and the complement of a positive number is the source code itself

The complement of # 10 is 0000, 1010, and the complement of # -10 is 1111 0110Copy the code

In a computer, numbers are stored and run as complement codes.

The meaning of the complement

There are two advantages to using complement as the actual storage mode of a computer over source code:

  1. We can unify the representation of the number 0. Since 0 is neither positive nor negative, it is difficult to determine whether 0 or 1 is used for the highest bit if the original code is used.

If represented by complement, we first treat 0 as a positive number, and its complement (source code itself) is expressed as follows:

0000, 0000,Copy the code

Let’s represent 0 as a negative number, and its complement (inverse + 1) is expressed as follows:

1111 1111 # complement 0000 0000Copy the code

As you can see from above, the binary representation of the final number is the same whether you treat it from a positive or negative point of view.

  1. Simplify addition and subtraction. Subtraction is calculated as addition to achieve the unity of positive and negative addition.

Let’s take 2 + 3 as an example:

Result: 0000 0101Copy the code

0000, 0101 is the decimal 5.

Take 2-3 as an example:

2's complement: 0000 0010-3's complement: 1111 1101 Result: 1111 1111Copy the code

So 1111, 1111 is minus 1 in decimal.

As we can see from the above example, when using complement to represent numbers, we do not need to distinguish positive and negative numbers, but only need to add the complement to get the result.