liveBook · Manning

Sign bit

As explained in Modern C, Third Edition

A sign bit is the bit in a signed integer representation that indicates whether the represented value is nonnegative or negative.

A sign bit is the additional bit in a signed integer representation that distinguishes nonnegative from negative values. A value with sign bit 0 is positive; with sign bit 1, it is negative. C23 permits only two’s-complement sign representation, where the upper half of the corresponding unsigned range is interpreted as negative. section 5.7.5

Negating a 16-bit pattern

For unsigned value 240, bitwise complement followed by one produces 65,296: ~240 + 1. In two’s complement, the resulting pattern has its high-order bit set and represents the corresponding negative value when interpreted as signed. section 5.7.5

bool is_negative(unsigned a) {
  constexpr unsigned int_max = UINT_MAX/2;
  return a > int_max;
}
bool is_signed_less(unsigned a, unsigned b) {
  if (is_negative(a) != is_negative(b)) return a > b;
  else return a < b;
}

Use the sign bit to classify an unsigned value: values above UINT_MAX/2 have a set high-order bit and compare as negative when interpreted as signed. section 5.7.5

How Modern C, Third Edition covers it

How deep it goes
Defines the sign bit and relates it to two’s-complement interpretation, while deferring detailed arithmetic and historical representations.
Examples
Uses a 16-bit negation table and functions that classify or compare unsigned values through their high-order bit.
What you can do after
Evaluate/understand whether an integer bit pattern is interpreted as positive or negative.
How it connects
Connects signed integers with unsigned integers, two’s complement, sign and magnitude, and one’s complement.

Also explained in

Compare how 2 books explain sign bit →

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.