How integers are stored in memory using two’s complement

Salah Besbes
3 min readNov 6, 2020

There are many schemes for representing negative integers with patterns of bits. One scheme is sign-magnitude. It uses one bit (usually the leftmost) to indicate the sign. “0” indicates a positive integer, and “1” indicates a negative integer. The rest of the bits are used for the magnitude of the number.

Two’s complement Method

let’s take an example : 7 = 0 1 1 1 : lets assume we work on a 4 bits

2^(4–1) = 2³ = 8
we have : 8 4 2 1
+ 7 = 0 1 1 1

in memory computer transform it into :

step 1 : reverse what u have ( every 0 changes to 1 and every 1 changes to 0 ).

First Complement: 1 0 0 0

step 2 : add 1 to the 1'st complement

  1 0 0 0
+ 1
___________
1 0 0 1
Second Complement: 1 0 0 1

the first bit on the left is telling us the sign of the number so :

-8 4 2 1
----------
1 0 0 1
----------
-8 + 1 = -7

lets take on other example :

to calculate the subtraction of 2 binary number on 7-bit-binary by using straight forward method:
(+39)-(+25)?

    0 1 2         
---------------
0 1 0 0 1 1 1 => 32 + 4 + 2 + 1 = 39
- 0 0 1 1 0 0 1 => 16 + 8 + 1 = 25
________________
0 0 0 1 1 1 0 => 8 + 4 + 2 = 14
----------------
64 32 16 8 4 2 1

this technique works but its a little bit long and can get confused let’s use Two’s complement Method: 39 + (-25)?

first lets convert the positive 25 ( 0 0 1 1 0 0 1 )to negative:

1'st comp: 1 1 0 0 1 1 0sec comp : 1 1 0 0 1 1 0
+ 0 0 0 0 0 0 1
_______________
1 1 0 0 1 1 1 => (-25)
------------------------
-64 + 32 + 0 + 0 + 4 + 2 + 1 = (-25)

now we can add 39 +(-25)

  0 1 0 0 1 1 1 
+ 1 1 0 0 1 1 1
________________
1 0 0 0 1 1 1 0 => 14
----------------
64 32 16 8 4 2 1

the first bit one the left is “ 1 “ is a carry over, because we didn’t have that many digit to begin with. We can just get rid ( ignore the over flow value ) of it because it is out of range.
so our real number is : 0 0 0 1 1 1 0 => 8 + 4 + 2 = 14

an other example : 43–71

1'st comp: 0 1 0 0 0 1 1 1sec comp : 1 0 1 1 1 0 0 0 
+ 0 0 0 0 0 0 0 1
__________________
1 0 1 1 1 0 0 1 => (-71)
0 0 1 0 1 0 1 1
+ 1 0 1 1 1 0 0 1
__________________
1 1 1 0 0 1 0 0
------------------
128 64 32 16 8 4 2 1
-128 + 64 + 32 + 4 = -28

To Resume

The MSB (most significant bit) bit is used to indicate whether the number is positive or negative.

How integers are stored in memory?

For positive numbers MSB will be 0.
For negative numbers MSB will be 1.

This binary equivalent of 65 will be stored in 32-bit memory like below,

How negative integers are stored in memory?

This 2’s complement form will be stored in computer.

--

--