{
  "id": "twos-complement",
  "title": "Two’s Complement",
  "lang": "en",
  "source_lang": "en",
  "summary": "Two’s complement is a fixed-width binary representation of signed integers that enables addition and subtraction using ordinary binary arithmetic.",
  "category": "computer-science",
  "subcategory": "hardware",
  "type": "concept",
  "aliases": [
    "Two's-complement representation",
    "Two’s-complement notation",
    "2’s complement"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/twos-complement/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/twos-complement/",
      "json": "https://aiwiki.page/zh/twos-complement.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Two’s complement is the predominant method of representing signed integers in computers. In a fixed-width binary word, the most significant bit has a negative positional weight, while the remaining bits have their ordinary positive weights. This arrangement represents positive numbers, negative numbers, and zero while allowing the same binary addition circuitry to handle both signed and unsigned operands. The term also denotes the operation of negating a binary value by inverting its bits and adding one, retaining only the specified number of bits."
    },
    {
      "heading": "Representation and range",
      "text": "For an \\(n\\)-bit word with bits \\(b_{n-1},\\ldots,b_1,b_0\\), its two’s-complement value is\n\n\\[x=-b_{n-1}2^{n-1}+\\sum_{i=0}^{n-2}b_i2^i.\\]\n\nThe most significant bit, \\(b_{n-1}\\), is commonly called the sign bit: it is 0 for nonnegative values and 1 for negative values. Unlike a separate sign attached to a magnitude, however, it participates directly in the positional-value calculation.\n\nThe representable range is\n\n\\[-2^{n-1}\\leq x\\leq 2^{n-1}-1.\\]\n\nAn 8-bit word therefore represents integers from \\(-128\\) through \\(127\\).\n\nBit pattern | Unsigned value | Two’s-complement value\n00000000 | 0 | 0\n00000001 | 1 | 1\n01111111 | 127 | 127\n10000000 | 128 | −128\n10000001 | 129 | −127\n11111110 | 254 | −2\n11111111 | 255 | −1\n\nThere is exactly one representation of zero. The range is asymmetric: it contains one more negative integer than positive integer.\n\nA bit pattern has no intrinsic signedness. For example, 11111111 can mean either unsigned 255 or signed \\(-1\\). Its interpretation depends on the instruction, data format, or type system being used."
    },
    {
      "heading": "Mathematical basis",
      "text": "Two’s complement is closely related to modular arithmetic modulo \\(2^n\\). An integer \\(x\\) is encoded as the unsigned binary representation of\n\n\\[u=x\\bmod 2^n, \\qquad 0\\leq u<2^n.\\]\n\nTo interpret that pattern as a signed integer,\n\n\\[x= \\begin{cases} u, & u<2^{n-1},\\\\ u-2^n, & u\\geq 2^{n-1}. \\end{cases}\\]\n\nThus, an \\(n\\)-bit negative integer \\(x\\) is encoded by the ordinary binary representation of \\(2^n+x\\).\n\nThis explains why fixed-width addition works for both signed and unsigned values: the underlying bit operation computes the same residue modulo \\(2^n\\). What differs is how the operands and result are interpreted, and whether the mathematical result lies within the chosen range.\n\nForming a negative value\n\nTo obtain the two’s-complement encoding of the negative of a value:\n\n- Invert every bit within the selected width.\n- Add one.\n- Discard any carry beyond that width.\n\nFor example, to encode \\(-5\\) in eight bits:\n\n 5:                 00000101\nInvert all bits:    11111010\nAdd one:            11111011\n\nInterpreted as unsigned, 11111011 equals 251; interpreted as two’s complement, it equals \\(251-256=-5\\).\n\nFor an unsigned pattern \\(u\\), inversion gives \\(2^n-1-u\\). Adding one therefore produces \\(2^n-u\\), which is congruent to \\(-u\\) modulo \\(2^n\\).\n\nThe width is essential. Inverting an 8-bit word and inverting a 16-bit word are different operations, even if their original nonnegative values are equal."
    },
    {
      "heading": "Addition and subtraction",
      "text": "Addition\n\nTwo’s-complement addition uses ordinary binary addition, retaining the lowest \\(n\\) bits. For example, \\(5+(-3)=2\\):\n\n    00000101       5\n  + 11111101      -3\n  ----------\n  1 00000010       2\n\nThe carry beyond the eight-bit word is discarded. Its presence does not, by itself, indicate signed overflow.\n\nThis shared arithmetic is a major hardware advantage. A central processing unit does not need separate addition circuits for positive and negative operands.\n\nSubtraction\n\nSubtraction follows the identity\n\n\\[a-b=a+(-b).\\]\n\nAt the bit level,\n\n\\[a-b\\equiv a+\\mathop{\\mathrm{NOT}}(b)+1\\pmod{2^n}.\\]\n\nAn arithmetic logic unit can therefore implement subtraction by conditionally inverting the second operand and supplying an initial carry of one. The same adder can support both addition and subtraction.\n\nSigned overflow\n\nInteger overflow occurs when an exact mathematical result is outside the representable range. In two’s-complement addition, signed overflow occurs precisely when operands with the same sign produce a retained result with the opposite sign.\n\nFor eight-bit arithmetic:\n\n  01111111       127\n+ 00000001         1\n----------\n  10000000      -128, if interpreted as two’s complement\n\nThe mathematical answer is 128, which is not representable as an 8-bit signed integer.\n\nBy contrast, adding \\(-1\\) and \\(1\\) produces an outgoing carry but no signed overflow:\n\n  11111111       -1\n+ 00000001        1\n----------\n1 00000000        0\n\nProcessors often distinguish an unsigned carry condition from a signed overflow condition. For binary addition, signed overflow can also be detected as the exclusive OR of the carry into and the carry out of the sign-bit position."
    },
    {
      "heading": "The minimum-value exception",
      "text": "The smallest representable integer, \\(-2^{n-1}\\), has no positive counterpart within the same width. Its encoding is a 1 followed by \\(n-1\\) zeros.\n\nFor eight bits:\n\nOriginal:          10000000      -128\nInvert:            01111111\nAdd one:           10000000\n\nThe modular negation operation returns the same bit pattern, although the mathematical result \\(128\\) is out of range.\n\nThis exception affects negation, absolute value, and division of the minimum integer by \\(-1\\). Depending on the processor instruction or programming language, such operations may wrap, raise an exception, or have undefined behavior.\n\nZero is the other bit pattern unchanged by fixed-width modular negation, but its negation does not overflow."
    },
    {
      "heading": "Changing the width",
      "text": "Sign extension\n\nTo widen a signed two’s-complement integer without changing its value, the new leading bits must repeat the original sign bit. This operation is called sign extension.\n\nFor example:\n\n8-bit -5:          11111011\n16-bit -5:         11111111 11111011\n\nNonnegative values acquire leading zeros; negative values acquire leading ones.\n\nZero extension is appropriate when preserving an unsigned value. Applying it to a negative two’s-complement pattern changes the signed value: zero-extending eight-bit 11111011 to sixteen bits produces positive 251 rather than \\(-5\\).\n\nTruncation\n\nNarrowing a bit pattern by discarding high-order bits preserves its residue modulo the new power of two. It preserves the signed mathematical value only if that value fits in the narrower range.\n\nFor example, truncating the 16-bit encoding of positive 200 to eight bits leaves 11001000, which represents \\(-56\\) as an 8-bit two’s-complement integer.\n\nA language-level narrowing conversion need not have exactly the same semantics as simply discarding bits; its behavior is determined by the language specification."
    },
    {
      "heading": "Shifts, multiplication, and division",
      "text": "Shifts\n\nAn arithmetic right shift replicates the sign bit in the newly vacated positions. For a shift by \\(k\\) positions, it computes\n\n\\[\\left\\lfloor\\frac{x}{2^k}\\right\\rfloor.\\]\n\nFor negative values this can differ from integer division that rounds toward zero. For example, arithmetic right-shifting \\(-3\\) by one position gives \\(-2\\), whereas division of \\(-3\\) by 2 with truncation toward zero gives \\(-1\\).\n\nA logical right shift instead inserts zeros and does not generally preserve the signed interpretation of a negative operand.\n\nAt the bit-pattern level, a left shift with excess high bits discarded corresponds to multiplication by a power of two modulo \\(2^n\\). Whether a signed shift expression is permitted, and what happens on overflow, depends on the programming language.\n\nMultiplication\n\nIf only the lowest \\(n\\) bits of a product are retained, signed and unsigned multiplication of the same operand patterns produce identical low-order bits. This follows from their equivalence modulo \\(2^n\\).\n\nTheir full-width products can differ. For example, eight-bit 11111111 multiplied by 00000010 means either:\n\n- \\(255\\times2=510\\), if interpreted as unsigned;\n- \\(-1\\times2=-2\\), if interpreted as signed.\n\nBoth products end in the same eight low-order bits, 11111110, but their 16-bit encodings differ.\n\nDivision and ordering comparisons require signedness-aware operations. Treating a negative encoding as a large unsigned number generally produces a different quotient or ordering."
    },
    {
      "heading": "Comparison with other signed representations",
      "text": "Two important alternatives are sign–magnitude representation and ones’ complement.\n\nProperty | Two’s complement | Ones’ complement | Sign–magnitude\n\\(n\\)-bit range | \\(-2^{n-1}\\) to \\(2^{n-1}-1\\) | \\(-(2^{n-1}-1)\\) to \\(2^{n-1}-1\\) | \\(-(2^{n-1}-1)\\) to \\(2^{n-1}-1\\)\nZero encodings | One | Two | Two\nNegation | Invert bits and add one | Invert bits | Toggle sign bit\nAddition | Ordinary fixed-width binary addition | End-around carry adjustment | Sign-dependent magnitude arithmetic\n\nEarlier computers used several signed-number representations. Two’s complement became dominant because it combines a unique zero, efficient sign extension, and relatively simple arithmetic circuitry.\n\nIts dominance for integers does not mean that all numerical formats use it. In particular, IEEE 754 floating-point formats encode a sign, exponent, and significand rather than representing the entire floating-point value as a two’s-complement integer."
    },
    {
      "heading": "Programming languages and data formats",
      "text": "Hardware representation and programming-language arithmetic are separate specifications. A machine may use two’s complement while a language still prohibits or leaves undefined certain overflowing expressions.\n\nIn C, the C23 standard requires two’s-complement representation for signed integer types; earlier standards also permitted sign–magnitude and ones’ complement. Signed arithmetic overflow remains undefined behavior under the ordinary C rules. Consequently, a compiler may optimize on the assumption that a valid execution does not encounter signed overflow, rather than preserving the processor’s apparent wraparound behavior.\n\nOther languages define different rules, including modular wraparound, checked arithmetic, or arbitrary-precision integers. Two’s complement alone does not determine those rules.\n\nFor serialized data, the representation must be considered alongside width, signedness, and byte order. Two’s complement specifies how a fixed-width bit pattern denotes a signed value; endianness specifies how the bytes of a multibyte value are ordered. Neither determines the other."
    }
  ],
  "links": [
    "computer",
    "bit",
    "type-system",
    "modular-arithmetic",
    "central-processing-unit",
    "integer-overflow",
    "ieee-seven-five-four",
    "c-programming-language",
    "compiler",
    "byte"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}