Ever wondered how a computer stores a negative number? It doesn't have a tiny "minus" symbol inside the hardware. π€
Instead, it uses a clever mathematical ritual called Twoβs Complement .
The "Flip and Add" Recipe π³
If you want to store -5 in an 8-bit char , the computer doesn't just put a sign in front. It follows these three steps:
Start with the Positive: Write 5 in binary $\rightarrow$ 00000101
Flip the Bits: Change every 0 to 1 and every 1 to 0 $\rightarrow$ 11111010
Add 1: Add a binary 1 to that result $\rightarrow$ 11111011
Boom! Thatβs exactly how -5 sits in your memory.
Why do we do this? (The Genius Part) π§
Why not just change the first bit to 1 and call it a day?
Because with Two's Complement , addition and subtraction work perfectly without any extra "brain power" from the CPU. When you add 5 ( 00000101 ) and -5 ( 11111011 ), the bits naturally add up to 0 (after a small overflow).
It turns subtraction into simple addition!β¦