Sikau

How computers work · Day 3 · about 35 min

Negative numbers

Two's complement: how one byte holds −128 to 127, and when addition overflows.

There's no minus switch

Bits have no minus sign. The trick every CPU uses is two's complement: the top bit is worth −128 instead of +128. Then 11111111 is −128 + 127 = −1, and ordinary addition just works for negative numbers too.

Negating and overflowing

To negate: flip every bit and add one. Adding works exactly like unsigned addition — the hardware doesn't care. But results can fall outside −128…127: adding two positives that gives a negative is overflow. A *carry* out of the top bit is a different thing (it matters for unsigned numbers).

function toSigned(byte) {
  return byte >= 128 ? byte - 256 : byte;
}

function negate(byte) {
  return (~byte + 1) & 0xff;
}

function addBytes(a, b) {
  const sum = a + b;
  const result = sum & 0xff;
  const carry = sum > 0xff;
  const sa = toSigned(a), sb = toSigned(b), sr = toSigned(result);
  const overflow = (sa < 0) === (sb < 0) && (sr < 0) !== (sa < 0);
  return { result, carry, overflow };
}

The rest of this lesson

  • Why flip and add one worksexplain
  • Overflow in real programsexplain
  • 8-bit arithmeticpredict
  • Negate a byteorder
  • Signed byteswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work