Digital arithmetic

2's complement

2's complement represents signed integers so addition and subtraction can use the same binary adder. The most significant bit has negative weight.

Level: FoundationRead: 5 minutesRelated: RTL arithmetic

Range and value

For N bits: range = -2^(N-1) to 2^(N-1) - 1
Value = -b[N-1] * 2^(N-1) + sum(b[i] * 2^i)
11101110

For an 8-bit signed value, the leftmost bit has weight -128 rather than +128.

How to negate a value

  1. Write the positive value at the required width.
  2. Invert every bit.
  3. Add one and keep the same width.
Represent -18 in 8 bits

+18 = 00010010. Invert = 11101101. Add one = 11101110, which is hexadecimal EE.

Negating 11101110 using the same steps returns 00010010.

Sign extension and overflow

When widening a signed value, copy the sign bit into the new upper bits. Signed addition overflows when two operands with the same sign produce a result with the opposite sign.

8-bit: 11101110 (-18)
16-bit sign-extended: 11111111 11101110 (-18)

Common mistakes

  • Forgetting to choose a fixed bit width before converting.
  • Treating the MSB as only a sign marker instead of a negative-weight bit.
  • Zero-extending a negative signed value.
  • Ignoring overflow when a result exceeds the selected range.