问题
As far as I know, the two's complement algo is:
1.Represent the decimal in binary.
2.Inverse all bits.
3.Add 1 to the last bit.
For the number 3
, which its representation is: 0000000000000011
the result of the two's complement would be 1111111111111101
which is -3
.
So far so good.
But for the number 2
which its representation is 0000000000000010
the result of the two's complement would be 1111111111111101
, which isn't 2 but -3.
What am I doing wrong?
回答1:
0...0010 // 2
1...1101 // Flip the bits
1...1110 // Add one
It works for negative too:
1...1110 // -2
0...0001 // Flip the bits
0...0010 // Add one
回答2:
For your code you might have needed to do 2's complement: i just wanted to throw this out there(a quicker way of getting a negative binary) :
2's complement is very useful for finding the value of a binary, however I thought of a much more concise way of solving such a problem(never seen anyone else publish it):
take a binary, for example: 1101 which is [assuming that space "1" is the sign] equal to -3.
using 2's complement we would do this...flip 1101 to 0010...add 0001 + 0010 ===> gives us 0011. 0011 in positive binary = 3. therefore 1101 = -3!
What I realized:
instead of all the flipping and adding, you can just do the basic method for solving for a positive binary(lets say 0101) is (23 * 0) + (22 * 1) + (21 * 0) + (20 * 1) = 5.
Do exactly the same concept with a negative!(with a small twist)
take 1101, for example:
for the first number instead of 23 * 1 = 8 , do -(23 * 1) = -8.
then continue as usual, doing -8 + (22 * 1) + (21 * 0) + (20 * 1) = -3
Hope that may help!
回答3:
What am I doing wrong?
Skipping step 3 for your second example (or misunderstanding it).
1111111111111101
is ones' complement of 2
(i.e. result of step 1 and 2); you need to add 1 - not to the last bit (as in binary digit), but to the last result (as in, what you get from step 2).
来源:https://stackoverflow.com/questions/13735443/twos-complement