How integers are stored in memory using two’s complement

Khalil Hassayoun
3 min readNov 5, 2020

An integer is a number with no fractional part; it can be positive, negative or zero. In ordinary usage, one uses a minus sign to designate a negative integer. However, a computer can only store information in bits, which can only have the values zero or one. So how do we store negative integers in a computer then?

Integer data types in C are typically 1, 2, 4 or 8 bytes in length, or 8, 16, 32, or 64 bits in length.

Integer types can be:

  • Unsigned: that can store values from 0 to 2^n -1, as simple binary numbers
  • Signed: that can store values from -(2^(n-1)) to 2^(n-1), as two’s complement binary format. Values greater than or equal to zer0 are stored with same bit values as unsigned numbers.

Decoding 2’s Complement Numbers

For positive values, if the leftmost (sign) bit is zero, the value is positive so simply do a binary to decimal conversion.

This example was run on 64-bit machine so there are about 57 zeros before this number so number is positive and the rest we calculate right to left as powers of two starting at zero and then multiplied by the bit at that power.

So going right to left we have;

0*²⁰ + 0*²¹ + 1*²² + 0*²³ + 1*²⁴ + 0*²⁵ + 1*²⁶

= 0 + 0 + 4 + 0 + 16 + 0 + 64 = 84

There are three steps necessary to convert a negative decimal integer to two’s complement form:

  1. Start with the positive binary value, expanded to fill the number of bits you will be storing the number into.
  2. Complement/flip all of the bits. This means all of the 1s become 0s and all of the 0s become 1s
  3. Add one to the flipped bits.

Interesting consequence in 2’s complement arithmetic

In unsigned arithmetic a carry of the most significant digit means that there has been an overflow, but in signed arithmetic an overflow is not so easy to detect. In fact, signed arithmetic overflows are detected by checking the consistency of the signs of the operands and the final answer.

A signed overflow can occur in an addition or subtraction if:

  • the sum of two positive numbers is negative;

sum of two positive numbers is negative

  • the sum of two negative numbers is non-negative;

sum of two negative numbers is non-negative

  • subtracting a positive number from a negative one yields a positive result;

subtracting a positive number from a negative one yields a positive result

  • subtracting a negative number from a non-negative one yields a negative result.

subtracting a negative number from a non-negative one yields a negative result

--

--

Khalil Hassayoun
0 Followers

Holberton school student . Future software engineer