Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need to add 1 while doing 2's complement

The 2's complement of a number which is represented by N bits is 2^N-number.
For example: if number is 7 (0111) and i'm representing it using 4 bits then, 2's complement of it would be (2^N-number) i.e. (2^4 -7)=9(1001)

7==> 0111
1's compliment of 7==> 1000
1000
+  1
-------------
1001 =====> (9)

While calculating 2's complement of a number, we do following steps: 1. do one's complement of the number 2. Add one to the result of step 1.

I understand that we need to do one's complement of the number because we are doing a negation operation. But why do we add the 1?

This might be a silly question but I'm having a hard time understanding the logic. To explain with above example (for number 7), we do one's complement and get -7 and then add +1, so -7+1=-6, but still we are getting the correct answer i.e. +9

like image 729
user85 Avatar asked Feb 12 '13 13:02

user85


Video Answer


2 Answers

Your error is in "we do one's compliment and get -7". To see why this is wrong, take the one's complement of 7 and add 7 to it. If it's -7, you should get zero because -7 + 7 = 0. You won't.

The one's complement of 7 was 1000. Add 7 to that, and you get 1111. Definitely not zero. You need to add one more to it to get zero!

The negative of a number is the number you need to add to it to get zero.

If you add 1 to ...11111, you get zero. Thus -1 is represented as all 1 bits.

If you add a number, say x, to its 1's complement ~x, you get all 1 bits.

Thus:
~x + x = -1

Add 1 to both sides:
~x + x + 1 = 0

Subtract x from both sides:
~x + 1 = -x

like image 165
David Schwartz Avatar answered Dec 20 '22 08:12

David Schwartz


The +1 is added so that the carry over in the technique is taken care of.

Take the 7 and -7 example.

If you represent 7 as 00000111

In order to find -7:

Invert all bits and add one

11111000 -> 11111001

Now you can add following standard math rules:

  00000111
+ 11111001
 -----------
  00000000

For the computer this operation is relatively easy, as it involves basically comparing bit by bit and carrying one.

If instead you represented -7 as 10000111, this won't make sense:

   00000111
+  10000111
  -----------
   10001110 (-14)

To add them, you will involve more complex rules like analyzing the first bit, and transforming the values.

A more detailed explanation can be found here.

like image 22
Next Door Engineer Avatar answered Dec 20 '22 10:12

Next Door Engineer