Two's Complement
Representing negative numbers in binary
In binary, we naturally represent positive numbers. But how do we represent negative numbers?
The most widespread solution is two's complement.
Two's complement allows using the same circuits to perform additions and subtractions, whether the numbers are positive or negative.
Principle
We choose a fixed size in bits (often 8, 16, 32 or 64 bits). The leftmost bit is called the sign bit:
0
means the number is positive1
means the number is negative
Two's complement allows encoding integers from to for bits.
For example, on 8 bits:
- min:
- max:
Calculating two's complement
To encode a negative number on bits:
- We encode in binary (positive) on bits
- We invert all bits (one's complement)
- We add 1 to the result
Two's complement of (on 8 bits):
- :
00000101
- Inversion:
11111010
- +1:
11111011
➜ this is the representation of-5
!
Why does it work?
Because we get consistent behavior with binary addition:
TODO
Warning in Python!
In Python, integers are not limited to 8 bits. Thus:
~255 = -256
This can cause errors if we expect an 8-bit result.
To simulate an 8-bit operation in Python:This keeps only the 8 rightmost bits (like a byte).
(~x) & 255
Two's complement and bounds
On 8 bits, possible values are:
Binary | Decimal |
---|---|
00000000 | 0 |
00000001 | 1 |
01111111 | 127 |
11111111 | -1 |
11111110 | -2 |
10000000 | -128 |
In two's complement on 8 bits, there are as many negative numbers as positive ones - except there's one more negative.
En complément à deux sur 8 bits, il y a autant de nombres négatifs que positifs - sauf qu'il y a un négatif de plus. ::