How can I perform multiplication without the '*' operator?

前端 未结 30 1615
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  孤街浪徒
    2020-12-01 02:32

    Think about how you multiply in decimal using pencil and paper:

      12
    x 26
    ----
      72
     24
    ----
     312
    

    What does multiplication look like in binary?

       0111
    x  0101
    -------
       0111
      0000
     0111
    -------
     100011
    

    Notice anything? Unlike multiplication in decimal, where you need to memorize the "times table," when multiplying in binary, you are always multiplying one of the terms by either 0 or 1 before writing it down in the list addends. There's no times table needed. If the digit of the second term is 1, you add in the first term. If it's 0, you don't. Also note how the addends are progressively shifted over to the left.

    If you're unsure of this, do a few binary multiplications on paper. When you're done, convert the result back to decimal and see if it's correct. After you've done a few, I think you'll get the idea how binary multiplication can be implemented using shifts and adds.

提交回复
热议问题