So today, in this article i will explain how are stored integers in memory, how the computer deals with negative and positive number using one complement and two’s complement.
Before to explain in details, what is an integer ? An integer is a positive/negative number, in the programming language C integers (signed) are stored in 4 bytes (32 bits), 1 bytes is 8 bits, with a max value : 2,147,483,647.
As you well know, computer are all about 0 and 1, so the base we will deal with will be base 2.
How can be stored in memory number 5 ?
As you can see, there is 4 bytes, the last byte this is where the number is but the integer 5 is all these 4 bytes in memory.
How can we know that this number in binary is positive and not negative?
A positive number in memory, start with a 0, like this:
A negative number in memory, start with a 1, like this:
So for now, to switch a positive number to a negative we just need to switch the first bits of the first bytes of the 4 bytes.
But, this is not exactly correct, to stored a negative number we use 1’s complements, what is that ?
1’s complements it’s just the logic that to store a negative number from a positive number, we don’t just add 1 at the first and let the rest, but we flip all the bits at their opposites:
And we switch all the bits:
So this is the negative number 5 in memory.
But 1’s complements, need one more thing, if you try to add number between them with 1’s complements (their binary representation) it will have a problem, the 1’s complements need adjustment with a ret 1.
So this is now that come Two’s complements, two’s complements it exactly the same as 1’s but add just +1 to the binary representation.
So now, if you want to add two number (positive and negative or whatever) take their two representation and add +1 at the start of your calculation and you will have the exact sum of this calculation.
This is it, i hope now you understand how are stored integers in memory, thanks to have reading me.