How can I multiply and divide using only bit shifting and adding?

后端 未结 14 1772
清歌不尽
清歌不尽 2020-11-22 15:09

How can I multiply and divide using only bit shifting and adding?

14条回答
  •  深忆病人
    2020-11-22 15:49

    Take two numbers, lets say 9 and 10, write them as binary - 1001 and 1010.

    Start with a result, R, of 0.

    Take one of the numbers, 1010 in this case, we'll call it A, and shift it right by one bit, if you shift out a one, add the first number, we'll call it B, to R.

    Now shift B left by one bit and repeat until all bits have been shifted out of A.

    It's easier to see what's going on if you see it written out, this is the example:

          0
       0000      0
      10010      1
     000000      0
    1001000      1
     ------
    1011010
    

提交回复
热议问题