Menu

πŸ•΅οΈβ€β™‚οΈ How Computers "Hide" a Minus Sign: The 2's Complement Trick
πŸ“°
0

πŸ•΅οΈβ€β™‚οΈ How Computers "Hide" a Minus Sign: The 2's Complement Trick

DEV CommunityΒ·LaibaΒ·about 1 month ago
#IWM8HHBm
#programming#cpp#softwareengineering#computer#bits#sign
Reading 0:00
15s threshold

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!…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More