liveBook · Manning

Two's complement

As explained in Modern C, Third Edition

Two's complement is a signed-integer representation in which the high-order bit contributes negative weight and the remaining bits contribute positive weights.

Two's complement represents signed integers by giving the high-order bit negative weight while the remaining bits retain positive weights. A zero sign bit denotes a nonnegative value; a one sign bit places the representation in the negative half of the corresponding unsigned range. C23 permits only this signed representation, replacing the historical alternatives of sign-and-magnitude and one's complement. section 5.7.5

Table 5.7 Negation for 16-bit unsigned integer types
Op Value b15 … b0
A 240 0b00000000’11110000
~A 65,295 0b11111111’00001111
+1 1 0b00000000’00000001
-A 65,296 0b11111111’00010000

Constructs the two's-complement negative of 240 by complementing every bit and adding one: ~A + 1. section 5.7.5

The representation uses the same bit operations as unsigned arithmetic; interpretation changes when the high-order bit is one. The supplied comparison functions classify that upper unsigned half as negative, then reverse the unsigned ordering only when the operands have different signs. section 5.7.5

TAKEAWAY

  • Positive signed values have the same representation as corresponding unsigned values. section 5.7.5
  • For an unsigned value A, compute its two's-complement negative as ~A + 1. section 5.7.5

How Modern C, Third Edition covers it

How deep it goes
Defines sign-bit interpretation, constructs negatives with ~A + 1, and demonstrates signed ordering across unsigned representations.
Examples
Uses 16-bit negation of 240 and functions that classify and compare unsigned values as signed.
What it assumes
Assumes familiarity with unsigned integer representations and bit operations.
What you can do after
Evaluate signedness and signed ordering from unsigned bit patterns, and construct negatives with bitwise operations.
How it connects
Connects signed integers with unsigned integers, sign bits, sign-and-magnitude, and one's-complement representations.

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, Third Edition. The section links point to the parts of the book it draws on.