Negating a Two's-Complement Bit Pattern

At a fixed width, complementing the bits and adding one computes the negative modulo the number of available patterns.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace four bits
  2. Test the lowest negative value
  3. Invert only within the announced width
  4. Test the one signed value whose positive counterpart does not fit

Trace four bits

Three is 0011. Its complement is 1100, and adding one produces 1101, which represents minus three in two's complement. Complementing the unsigned value first subtracts that value from 15.

Test the lowest negative value

Negating 1000 gives 1000 again at width four. The mathematical result eight is outside the signed field. A program needs the language's actual bounded integer semantics before treating this wrap as valid.[1]

Invert only within the announced width

For a five-bit word representing seven, invert 00111 to 11000 and add one, obtaining 11001. Decoded under the same signed rule, that is minus seven. This calculation implements an additive inverse modulo thirty-two. See reading two's complement.

00111 → invert → 11000
11000 + 00001 = 11001
00111 + 11001 = 1 00000
Low five bits of the sum: 00000

Test the one signed value whose positive counterpart does not fit

In five bits, negating 10000 returns the same pattern after wraparound. Minus sixteen lacks a positive sixteen in the signed range. State whether the language or format wraps, traps or widens.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩