问题
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
回答1:
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
回答2:
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.
回答3:
Short answer: If you don't add 1
then you have two different representations of the number 0
.
Longer answer: In one's complement
the values from
0000
to0111
represent the numbers from0
to7
the values from
1111
to1000
represent the numbers from0
to-7
- since their inverses are
0000
and0111
.
- since their inverses are
There is the problem, now you have 2 different ways of writing the same number, both 0000
and 1111
represent 0
.
If you add 1 to these inverses they become 0001
and 1000
and represent the numbers from -1
to -8
therefore you avoid duplicates.
来源:https://stackoverflow.com/questions/14833773/why-we-need-to-add-1-while-doing-2s-complement