All modern computers use 2‘s complement for integer representation.

This encoding gives us only a single representation for zero, and binary addition is much easier than with Signed magnitude because we can just add sequences.

The downside is that we can represent one more negative number than positive (because zero takes up one “spot” on the positive side).

Intuition

the computer only needs to be able to add binary sequences. it does not know or need to care what the two patterns it’s adding actually represent.

so, we should set things up so that when the binary sequences are added, the resulting bit sequence also represents the correct resulting sum.

positive

the specification for positive integers remains the same as 1’s complement. if we have bits, we use half of the possible numbers to represent values from to .

takes up one spot, so the value of can’t be represented.

negative

to get the negative equivalent of the same number, we first flip the bits and then add a 1 to the bit sequence. note that we’re not adding to the representation of the value, just the literal binary.

…and back

and actually, switching between the positive and negative counterpart follows the same procedure.

  1. flip all the bits.
  2. add 1 to the sequence.

really nice properties

we can repeatedly add 1 to the bit sequences to also get the next integer representation.

Example

if we have a 5-bit system, we can move from to , cross the line over to , and reach by continually adding 1.

when adding the binary sequences of, let’s say and , the resulting bit sequence represents . adding complements cancels out even in binary!

Note

notice that adding and technically produces , a 6-bit number. however, in 2‘s complement we can always ignore the carry bit.

Subtraction

As an extension of how easy addition is, subtraction becomes trivial well. Every can be rewritten as , and we know how to negate , so to the ALU every subtraction becomes another addition operation.

Integer overflow

2‘s complement also enables easy hardware logic for checking overflow. This occurs when the sign of the number suddenly changes.

  • When adding two positive numbers produces negative sum
  • When adding two negative numbers produces positive sum

In the ALU, this is detected when in the most significant bit of the adder.

precision extension

integer precision is determined by the number of bits used in representation. most computers today support 32-bit integers or 64-bit integers.

we extend precision here by extending the sign bit to the left. that is, we fill in the remaining bits with either 0 or 1. we will be told what integer representation is used for the given bit string.

in the same way that leading zeroes does not affect the value of positive numbers, leading ones does not affect the value of negative numbers.