How to perform multiplication, using bitwise operators?

前端 未结 7 1912
一个人的身影
一个人的身影 2020-12-04 13:28

I am working through a problem which i was able to solve, all but for the last piece - i am not sure how can one do multiplication using bitwise operators:

0         


        
7条回答
  •  星月不相逢
    2020-12-04 13:56

    To multiply two binary encoded numbers without a multiply instruction. It would be simple to iteratively add to reach the product.

    unsigned int mult(x, y)
    unsigned int x, y;
    {
        unsigned int reg = 0;
    
        while(y--)
            reg += x;
        return reg;
    }
    

    Using bit operations, the characteristic of the data encoding can be exploited. As explained previously, a bit shift is the same as multiply by two. Using this an adder can be used on the powers of two.

    // multiply two numbers with bit operations
    
    unsigned int mult(x, y)
    unsigned int x, y;
    {
        unsigned int reg = 0;
    
        while (y != 0)
        {
            if (y & 1)
            {
                reg += x;
            }
            x <<= 1;
            y >>= 1;
        }
        return reg;
    }
    

提交回复
热议问题