In binary, we naturally represent positive numbers. But how do we represent negative numbers?
The most widespread solution is two's complement.
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 negativeTwo's complement allows encoding integers from to for bits.
For example, on 8 bits:
To encode a negative number on bits:
000001011111101011111011 ➜ this is the representation of -5!Because we get consistent behavior with binary addition:
TODO
In Python, integers are not limited to 8 bits. Thus:
~255 = -256
This can cause errors if we expect an 8-bit result.
(~x) & 255
On 8 bits, possible values are:
| Binary | Decimal |
|---|---|
00000000 | 0 |
00000001 | 1 |
01111111 | 127 |
11111111 | -1 |
11111110 | -2 |
10000000 | -128 |
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. ::