how to do two complement multiplication and division of integers?

前端 未结 2 582
情歌与酒
情歌与酒 2020-12-24 14:43

I have read this post on binary multiplication using two complement. but it is not very clear to me. Even I have difficulty understanding the wiki article on this. I want to

2条回答
  •  囚心锁ツ
    2020-12-24 14:46

    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.

提交回复
热议问题