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
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 get1111. 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
1to...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