Two's complement representation of negative numbers
I will explain the two's complement expression for expressing negative numbers.
This is explained using the example of int8_t, which is an 8-bit signed integer type.
In computer architecture, there are several ways to represent negative numbers. Two's complement representation is one of them.
Let's write out the two's complement expression concretely.
| Negative number | Negative number bit representation | Positive number (including 0) | Positive number bit representation < / td> |
| -1 | 11111111 | 0 | 00000000 |
| -2 | 11111110 | 1 | 00000001 |
| -3 | 11111101 | 2 | 00000010 |
| ... | ... | ... | ... |
| -126 | 10000010 | 125 | 01111101 |
| -127 | 10000001 | 126 | 01111110 |
| -128 | 10000000 | 127 | 01111111 |
Let's take a look at the characteristics of 2's complement representation.
- A positive number if the most significant bit is 0. Negative number if the most significant bit is 1
- 127 (maximum positive value) is 01111111
- -1 is 11111111
- -128 is 10000000
- Inverting the bits and summing them gives -1 (11111111)
The definition of 2's complement can be found everywhere, so please check it out (laughs).
Can we assume that negative numbers are two's complement representations?
The C language specification does not define a negative number as a two's complement, but in many implementations, the representation of a negative number is much more two's complement than any other representation. think.
If you get a negative minimum when you add 1 to the positive maximum, you can be confident that your implementation is using 2's complement representation for negative numbers.
If the Numerical Library requires the implementation to have a two's complement as a negative representation, it can be checked with a simple calculation.
What are the characteristics of 2's complement?
The feature of 2's complement is that subtraction can be expressed by addition.
2-3 = -1
This is the same as below.
# 00000010 + 11111101 = 11111111 2 + (-3) = -1
Where is the nuance of 2's complement 2?
The naming method may have been wrong ...
I think forcibly.
Let's call the first discovered complement the one's complement. The sign changes by mere bit inversion.
Let's call the second found complement the two's complement. If you add 1 to the simple bit inversion, the sign will change.
C Language Zemi