#1,113 – Addition of Integers Using Twos Complement

The primary benefit of using twos complement to represent signed integers is that addition and subtraction work the same, whether the number is positive or negative.

Below is an example, showing how we add the value -2 to the value +5, yielding a result of +3.  (Assuming that both values are stored as 16-bit integers).  The carry bits are shown in the top line.  We discard the final carry bit that results from adding the leftmost two bits.

1113-001

#1,112 – How Integers Are Stored in .NET

Integer values in .NET are stored in memory as described below.  The examples below use a 2-byte short data type as an example.

A value of zero is stored by setting every bit in the storage location to zero.

Positive values are stored directly as their corresponding binary number.

1112-001

The maximum possible integer value has all bits set to 1 except for the leftmost.  So Max = 2^(n-1) – 1, where n is the total number of bits.

Negative integer values are stored using a two’s complement representation, calculated by starting with the bit pattern for the corresponding positive number, negating all of the bits, and then adding 1 to the result.

1112-002

The minimum possible integer value (largest negative value) has only the leftmost bit set to 1.  So Min = -(2^(n-1)), where n is the total number of bits.