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
5in binary $\rightarrow$00000101 - Flip the Bits: Change every
0to1and every1to0$\rightarrow$11111010 - Add 1: Add a binary
1to 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! β
β οΈ The "Unsigned" Trap
This is the part Love Babbar often emphasizes: If you use an unsigned variable, you are telling the computer: "Ignore the minus sign glasses!" π
If you store -5 in an unsigned variable, the computer sees that leading 1 and thinks it's a massive number (like 4 billion) instead of a negative sign.
Key Lesson: Bits are just bits. Itβs the Data Type that tells the computer how to read them!
π Shoutout
Huge thanks to Love Babbar for the "Code Help"! π His explanation of how memory actually interprets these bits is a game-changer for understanding C++ foundations.
What concept should I dive into next? DBMS or more C++ quirks? π
Top comments (0)