Two's complement and negative numbers
People need computers to store their information, but did you ever ask yourself how are these information stored in the memory of the computer ? Well in today’s blog we are going to focus on integers only and explain how they are stored in the memory.
The binary representation of an integer have an MSB which (most significant bit) which is a sign bit. If it’s 1 that mean that the integer is negative, if it’s positive it mean that the integer is positive.
Let's consider a first example with a negative MSB, that means in the case of a positive integer, in this case we just do a simple binary to decimal conversion
Example:
$ export "BINARY"=1010 $echo $[2#BINARY] 10
And that’s how we got this 84
02¹ + 02³ = 0 + 2 + 0 + 8 = 10
That positive integer that we got have a one complement which is in binary form
Now let’s take a look on how to convert that one complement integer to two’s complement integer.
If i want to convert a one complement positive integer to two’s complement negative integer:
Start with the positive binary value Complement/flip all of the bits. This means all of the 1s become 0s and all of the 0s become 1s Add one to the flipped bits.
And here is an example:
And here is a more detailed explanation of the above steps:
Step 1. 10 = 0…000…0000001010.
Step 2. 1…111…1111111010.
Step 3. add 1 so we get 1…111…1111110101 So we have 1…111…1111110101 just like in screenshot above.