Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

binary - Adding and subtracting two's complement

Using six-bit one's and two's complement representation I am trying to solve the following problem:

12 - 7 

Now, i take 12 in binary and 7 in binary first.

12 = 001100 - 6 bit 
7 =  000111 - 6 bit

Then, would I then flip the bit for two's complement and add one?

12 = 110011 ones complement 
     +    1
    -------
     001101

7  = 111000 ones complement 
    +     1
   ---------
      111001

then, add those two complement together

 001101
+111001
-------
1000110 = overflow? discard the last digit?  If so I get 5

Now, if I have a number like

-15 + 2

I would then add a sign magnitude on the MSB if it's a zero?

like:

-15 = 001111 6 bit

Would I add a 1 at the end here before I flip the bits?

  = 101111
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using two's complement to represent negative values has the benefit that subtraction and addition are the same. In your case, you can think of 12 - 7 as 12 + (-7). Hence you only need to find the two's complement representation of -7 and add it to +12:

12  001100
-7  111001   -- to get this, invert all bits of 7 (000111) and add 1
----------
 5 1000101

Then discard the carry (indicates overflow), and you have your result: 000101 which equals to 5 as expected.

For your example of -15 + 2, simply follow the same procedure to get the two's complement representation of -15:

15  001111
    110000   -- inverted bits
    110001   -- add 1

Now do the addition as usual:

-15  110001
  2  000010
-----------
res  110011

To see that res indeed equals -13, you can see that it is negative (MSB set). For the magnitude, convert to positive (invert bits, add 1):

res  110011
     001100  -- inverted bits
     001101  -- add 1

Hence the magnitude is 13 as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...