Two's Complement: Signed Binary Numbers
Understand two's complement representation for signed integers. Learn how to convert between positive and negative binary values with clear, worked examples.
Detailed Explanation
Two's complement is the standard method computers use to represent signed (positive and negative) integers. It elegantly handles negative numbers using the same binary addition hardware that works for positive numbers.
How two's complement works:
In an n-bit two's complement system, the most significant bit (MSB) is the sign bit: 0 for positive, 1 for negative. For an 8-bit number:
- Positive range:
00000000to01111111(0 to +127) - Negative range:
10000000to11111111(-128 to -1)
Converting a positive number to its negative (finding two's complement):
To negate a number, invert all bits then add 1:
Example — finding -42 in 8-bit two's complement:
- Start with +42:
00101010 - Invert all bits:
11010101 - Add 1:
11010110
So -42 is represented as 11010110₂.
Converting two's complement back to decimal:
If the MSB is 1 (negative number), invert all bits and add 1 to get the magnitude:
- Given:
11010110 - MSB is 1, so it is negative
- Invert:
00101001 - Add 1:
00101010= 42 - Result:
-42
Why two's complement is brilliant:
The key advantage is that addition works identically for signed and unsigned numbers. The CPU does not need separate circuits for signed vs. unsigned addition. For example, 5 + (-3):
00000101 (+5)
+ 11111101 (-3)
----------
100000010
Discard the carry beyond 8 bits: 00000010 = 2. Correct.
Common ranges:
| Bits | Signed Range | Unsigned Range |
|---|---|---|
| 8 | -128 to +127 | 0 to 255 |
| 16 | -32,768 to +32,767 | 0 to 65,535 |
| 32 | -2,147,483,648 to +2,147,483,647 | 0 to 4,294,967,295 |
Use Case
Firmware developers use two's complement arithmetic when reading signed sensor values like temperature (-40 to +125 degrees) from hardware registers that return raw binary data.
Try It — Number Base Converter
Related Topics
Binary Arithmetic: Addition and Subtraction
Binary (Base 2) → Binary (Base 2)
Convert Binary to Decimal
Binary (Base 2) → Decimal (Base 10)
Convert Decimal to Binary
Decimal (Base 10) → Binary (Base 2)
Bit Shifting: Left Shift and Right Shift Operations
Binary (Base 2) → Binary (Shifted)
IEEE 754 Floating Point Binary Representation
Decimal (Floating Point) → Binary (IEEE 754)