Lably
Skip to content

Two's complement

Binary representation for signed numbers

  • 26 min read
  • 11 chapters

Learn it on Lably

Unlike the ones' complement scheme, the two's complement scheme has only one representation for zero, with room for one extra negative number (the range of a 4-bit number is −8 to +7). Furthermore, the same arithmetic implementations can be used on signed as well as unsigned integers and differ only in the integer overflow situations, since the sum of representations of a positive number and its negative is 0 (with the carry bit set).

All modern computers use two's complement, and thus standards such as C++20 and C23 require that representation.

Procedure

The following is the procedure for obtaining the two's complement representation of a given negative number in binary digits:

  • Step 1: starting with the absolute binary representation of the number, with the leading bit being a sign bit;
  • Step 2: inverting (or flipping) all bits – changing every 0 to 1, and every 1 to 0;
  • Step 3: adding 1 to the entire inverted number, ignoring any overflow. Accounting for overflow will produce the wrong value for the result.

For example, to calculate the decimal number −6 in binary from the number 6:

  • Step 1: +6 in decimal is 0110 in binary; the leftmost significant bit (the first 0) is the sign (just 110 in binary would be −2 in decimal).
  • Step 2: flip all bits in 0110, giving 1001.
  • Step 3: add the place value 1 to the flipped number 1001, giving 1010.

To verify that 1010 indeed has a value of −6, add the place values together, but subtract the sign value from the final calculation. Because the most significant value is the sign value, it must be subtracted to produce the correct result: 1010 = −(1×23) + (0×22) + (1×21) + (0×20) = 1×−8 + 0 + 1×2 + 0 = −6.

Steps 2 and 3 together are a valid method to compute the additive inverse −n of any (positive or negative) integer n where both input and output are in two's complement. An alternative to compute −n is to use subtraction 0−n. See below for subtraction of integers in two's complement.

Sign in to keep reading

10 more chapters are free with a Lably account.

More in Computing and communication