Course contentsShow
← C
Lesson 91 of 1,2192. Variables and TypesFree lesson

How bits represent negative numbers

How bits represent negative numbers

What you'll learn: How computers use a trick called Two's Complement to store negative values using only ones and zeros.

The problem with minus signs

In the physical world, we write a "-" symbol to show a number is negative. Computers, however, only have bits (0 and 1). They can't store a "dash." To solve this, C uses a system called Two’s Complement.

Imagine a circular tally counter, like the odometer in an old car. If the display shows 000 and you drive backward one mile, the numbers roll back to 999. In the world of bits, we treat these "rolled back" patterns as negative numbers.

The sign bit

In a signed integer, the leftmost bit is the "Sign Bit."

  • If it is 0, the number is positive.
  • If it is 1, the number is negative.

However, a negative number isn't just a positive number with the first bit flipped. If 00000001 is 1, then 10000001 is not -1. Instead, we use a mathematical "flip and add" shortcut to find the negative bit pattern.

How to flip a number

To represent a negative number (like -5) in binary, follow these two steps:

  1. Invert: Flip every bit (0 becomes 1, 1 becomes 0).
  2. Add One: Add 1 to the result.
// Concept: How -5 looks in an 8-bit signed char
// Start with +5:    00000101
// 1. Flip bits:     11111010
// 2. Add one:       11111011 (This is -5)

Why do we do this?

This system is brilliant because it makes math easy for the computer's hardware. By using Two's Complement, the computer can perform subtraction by simply adding a negative bit pattern to a positive one.

For example, 5 + (-5) using the patterns above would result in 00000000 (after the final "carried" bit drops off the end). The computer doesn't need a separate "subtraction brain"; it just adds specific patterns of ones and zeros to get the correct result every time.

Key takeaway

Negative numbers are stored by flipping the bits of a positive number and adding one, allowing the computer to treat subtraction as a simple addition.