liveBook · Manning

Two's complement

As explained in Modern C

Two's complement representation encodes negative integers by complementing the corresponding positive representation and adding one, with the high-order bit indicating negativity.

Two's complement represents a negative integer by applying the same bit arithmetic used for unsigned integers and interpreting a representation with a high-order 1 as negative. For an unsigned value A, its negation is computed as ~A + 1. The sign bit is 0 for nonnegative values and 1 for negative values. section 5.7.5

Negating 240 in 16 bits

Start with A = 240, represented as 0000000011110000. Complement every bit to obtain ~A = 65295, or 1111111100001111. Add one: ~A + 1 = 65296, represented as 1111111100010000. Under two's complement interpretation, that bit pattern represents -240. section 5.7.5

Keep these distinctions in view:

  • C permits sign-and-magnitude, ones' complement, and two's complement representations; the first two permit both positive and negative zero. section 5.7.5
  • Fixed-width intN_t types, when provided, use two's complement, have exactly N bits, and provide N − 1 bits of value precision. section 5.7.6

How Modern C covers it

How deep it goes
Works through bit-level negation and contrasts three sign representations, but stops short of a full signed-arithmetic treatment.
Examples
Uses a 16-bit negation table, the identity ~A + 1, and fixed-width int64_t expressions.
What it assumes
Assumes unsigned arithmetic and introduces sign bits and alternative signed representations in context.
What you can do after
Evaluate signed bit patterns and compute negative values using complement-and-add-one reasoning.
How it connects
Connects signed integers with unsigned integers, sign bits, ones' complement, sign and magnitude, and fixed-width integer types.

Also explained in

Compare how 4 books explain two's complement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.