Signed bytes
A byte is 8 bits, so it has 2 to the power 8 = 256 patterns. Read as plain binary, they mean 0 to 255. The back row holds 5: 00000101, which is the 4 bit plus the 1 bit.
First idea: let the top bit be a minus sign, so 10000101 means −5. This is called sign and magnitude. But it has two zeros, 00000000 and 10000000, and plain binary addition gives wrong sums. Computers use a cleverer rule.
Two's complement keeps every place the same except the top one: it is worth −128 instead of 128. So 10000000 is −128, and 11111111 is −128 + 127 = −1. Small positive numbers keep their usual bits.
Negating 5
To turn 5 into −5, first flip every bit: each 0 becomes 1 and each 1 becomes 0. 00000101 becomes 11111010, which is −6. Python's ~ operator does this flip: ~5 gives −6.
Then add 1: 11111010 + 1 = 11111011, and that is −5. Why? A number plus its flipped copy is always 11111111, which is −1. So the flip is one short, and adding 1 fixes it.
Check it with the place values. The 1 bits are worth −128, 64, 32, 16, 8, 2 and 1. Adding them gives −128 + 123 = −5. The top bit says negative; the rest say how far above −128.
Adding
Now add 5 and −5 column by column, right to left, as on paper. 1 + 1 = 10 in binary: write 0, carry 1. Every column after that also makes 10, so the carry ripples out of the left end.
The full answer, 100000000, needs 9 bits, but a byte has only 8. The extra carry falls off and is lost, leaving 00000000, which is 0. So 5 + (−5) = 0, using the same adder as for positive numbers.
Range and code
Eight bits in two's complement hold −128 to 127: still 256 patterns, now half of them negative. The largest is 01111111 = 127, the smallest is 10000000 = −128. A top bit of 1 always means negative.
Python integers have no fixed size, so −5 shows with a minus sign. To see its 8-bit pattern, keep the low 8 bits with & 0xFF: −5 & 0xFF is 251 (0b11111011). If it is 128 or more, subtract 256 to read it back.
Try it in the Python prompt
;; step 1/10 · A byte holds 256 patterns >>> 2**8 # patterns in one byte 256 >>> 0b00000101 5
Why flip and add one works: x plus its flipped copy is always 11111111, which is −1. So the flip equals −x − 1, and adding 1 gives −x. Python defines ~x the same way, as −(x + 1). The name: as plain binary, −x is stored as 2^8 − x, its complement with respect to 2^8 = 256. For 5 that is 256 − 5 = 251 = 11111011.