Binary 2's Complement Tutorial: how integers are stored in memory

David Peralta
3 min readAug 9, 2019

--

Welcome again!!

In this blog, I’m going to talk about how integers are stored in the computer, as you know all we can see on our screen is actually the result of binary machine code converted to numbers, letters, images, etc.

Storage is a complex process but we can say that basically the computer takes the data, convert it in a binary number and store it in the hardware of the computer, then it can be organized and used by the programs, note that this is a very simple way to describe it. Binary is a set of 0’s and 1’s, for the machine, it means on or off, true or false.

Why binary?

All data in the computer is stored like numbers, letters for example usually have a numeric value (ASCII), images are more complex, but actually is a colo represented in number value that is in a certain pixel position, this is a number also.

Integers

Numbers are stored in blocks, these blocks are defined by the corresponding data type, so for example, integers are usually stored in blocks of 1 byte or 8 bits, 2 bytes or 16 bits, 4 bytes or 32 bits, or 8 bytes or 64 bits and so on (each byte have 8 bits). Let’s take a 4 bytes integer piece of data, So imagine there are 32 spaces, in each one you can store a ‘0’ o a ‘1’, so which is the biggest number we can store?

Binary and Integer

As you can see in the image there are four integers numbers and its corresponding binary, but note that all 32-bit space is full with ‘0’ or ‘1’, so the biggest number that can be stored in a 32-bit space is +2.147'483.647.

(2 ³¹)-1 which takes 31 bits in its representation in binary.

MSB example

98 is actually 1100010, preceded by 0’s. This is how is represented under the ‘hood’. Note in the example that there are negative numbers, in binary, we define positive numbers starting with a ‘0’ and ‘1’ for negative, that first number is actually the Most Significant Bit or MSB.

The MSB, also know as the high-order bit or left-most bit, correspond to the bit sign.

1’s complement is basically the ‘inverted’ binary number, it means, the 0 changed by 1 in each bit position.

Example:

10 in Binary representation is 1010

1’s compliment is 0101 (8 bit)

The 2’s complement is a way to represent the negative number in binary, it is calculated finding the 1’s complement and adding 1.

Example:

10 in Binary representation is 00001010

1’s compliment is 11110101

2’s compliment (adding 1) is 11110110, that is -10

CONCLUSION

This is an easy way to manipulate binary and get the negative corresponding number. When compiling the machine handle the MSB, so it gets the corresponding sing, and there is a simple way to understand how the representation.

--

--