Signed Representation: Two's Complement
Learning Outcomes
- Translate between decimal numbers and two’s complement representations
- Compare two’s complement to other signed and unsigned representations
🎥 Lecture Video
Two’s Complement
Ones’ complement:
- Problem: Negative mappings “overlap” with the positive ones, creating the two 0s.
- The solution: Shift the negative mappings left by one.
“Binary odometer” for 4-bit twos’ complement.
Of note:
- Like in ones’ complement, incrementing the binary odometer corresponds with integer addition by one.
0b0000is still .- Positive numbers are the same as ones’ complement.
- Negative numbers are shifted over! For example,
0b1111now maps to . This gives us one extra negative number. - The most significant bit (leftmost bit) can still be interpreted as the sign bit.
In Two’s Complement, a bit pattern of all ones is .
Show Answer
- Zero: 1
- Positive:
- Negative:
Arithmetic and conversion
Hardware for two’s complement is now simple.
Addition is exactly the same as with an unsigned number.
The numbers and are represented in 4-bit two’s complement with 0b0101 and 0b1011, respectively. Adding them together should result in , or 0b0000.
Addition in two’s complement follows the decimal intuition.
Explanation
Work right-to-left:
1+1=0carry11+0+1=0carry11+1+0=0carry11+0+1=0carry11(is truncated and dropped in 4-bit representation)
(Double check that binary math matches decimal math: )
Formal definition
We can write the value of an -digit two’s complement number as
Positive and negative numbers can be computed using the same formula. Above, the sign is computed by multiplying the highest bit by .
Example: and in 4-bit two’s complement
Two’s Complement: Flip sign
Hardware to convert positive to negative (& vice versa) is simple.
- Complement all bits
- Then add 1
Two’s Complement: To change sign, flip the bits and add one.
At home: Prove algorithm is equivalent to formula!
The intuition comes from a “number wheel” representation of our binary odometer (Figure #fig-twos-complement-number-wheel). This wheel also helps us understand identify where integer overflow occurs:
Top: A number line indicating where integer overflow occurs. Bottom: A number “wheel” indicating the same integer overflow location.
In #fig-twos-complement-number-wheel, 0 through 7 stays the same as it has for every representation. But then it jumps to . That cool top-level term () pulls all negative numbers down by one so there is no overlap at zero.
Two’s Complement: C standard (as of 2025)
Two’s complement is the C23 standard number representation for signed integers. Again, the built-in int is ambiguous because it does not specify bitwidth. And again, the header stdint.h accommodates typedefs like int8_t, int16_t, int32_t, etc., for signed integer representations.