how to do two complement multiplication and division of integers?

别说谁变了你拦得住时间么 提交于 2019-11-30 03:45:06

step 1: sign extend both integers to twice as many bits. This is safe to do, though may not always be necessary.

for 4-bit --> 1111, you would extend as 1111 1111
for 4-bit --> 0111,you would extend as 0000 0111

step 2: do elementary multiplication

sep 3: take the correct number of result bits from the least significant portion of the result.

eg: after multiplication, you end up with something such as 0010011110take the last 8 bits i.e 10011110

Let me illustrate with the example you provided: -1 X -7 in 4-bit representation

         1111 1111        -1
       x 1111 1001     x  -7
      ----------------    ------
          11111111         7
         00000000
        00000000
       11111111
      11111111
     11111111
    11111111
   11111111
   ----------------
1  00000000111       --->  7 (notice the Most significant bit is zer``o)
      --------  (last 8-bits needed) 

you could get more details here;

for division: convert to positive and after the calculation adjust the sign. I will leave this as exercise but you could refer this page.

Okay, let's see if I can make this simple enough for you.

Two's complement: IFF (If and only if) you have a negative number, first put it into the positive form. For sake of simplicity, all numbers will be 6 bit. The limit of the bits will limit how big your numbers can go. Besides that, what the size is doesn't matter.

Some numbers converted to their positive binary form -7: 000111 16: 010000 -22: 010110 1: 000001

Now for -7 and -23 ONLY we'll do two's complement on. So we flip the bits (1 -> 0 && 0 -> 1) and then add one.

 000111
 Goes to the complement + 1
 111000
 +    1
=111001

And for 22

 010110
 Goes to the complement + 1
 101001
+     1
=101010

Then you just add them together like you would any other number.

And it looks like somebody else already covered the multiplication part, so I won't bother repeating that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!