🕵️‍♂️ How Computers “Hide” a Minus Sign: The 2’s Complement Trick

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:

  1. Start with the Positive: Write 5 in binary $rightarrow$ 00000101
  2. Flip the Bits: Change every 0 to 1 and every 1 to 0 $rightarrow$ 11111010
  3. 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! ➕

⚠️ 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? 👇

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

To buy this Bay Area home, you’ll need Anthropic equity

Related Posts