如何使用按位运算符执行乘法?

时间:2010-09-15 21:33:36

标签: bit-manipulation multiplication

我正在解决一个我能够解决的问题,除了最后一块之外 - 我不确定如何使用按位运算符进行乘法运算:

0*8 = 0

1*8 = 8

2*8 = 16 

3*8 = 24 

4*8 = 32

您能否推荐一种方法来解决这个问题?

7 个答案:

答案 0 :(得分:36)

要将任何值2乘以N的幂(即2 ^ N),将比特向左移位N次。

0000 0001 = 1 

times 4 = (2^2 => N = 2) = 2 bit shift : 0000 0100 = 4

times 8 = (2^3 -> N = 3) = 3 bit shift : 0010 0000 = 32

等。

将位移到右侧。

这些位是整数1或0 - 如果你乘以的数字不是N的整数值,你就不能按位的一部分移位 即。

since: 17 = 16  + 1 
thus:  17 = 2^4 + 1

therefore: x * 17 = (x * 16) + x in other words 17 x's  

因此,要乘以17,你必须向左移动4位,然后再次添加原始数字:

==> x * 17 = (x * 2^4) + x 
==> x * 17 = (x shifted to left by 4 bits) + x 

so let x = 3 = 0000 0011 

times 16 = (2^4 => N = 4) = 4 bit shift : 0011 0000 = 48

plus the x (0000 0011)

    0011 0000  (48)  
+   0000 0011   (3)
=============
    0011 0011  (51)

编辑:更新到原始答案。 Charles Petzold has written a fantastic book 'Code'将以最简单的方式解释所有这些以及更多内容。我完全推荐这个。

答案 1 :(得分:10)

在没有乘法指令的情况下乘以两个二进制编码数。 迭代添加以获得产品会很简单。

unsigned int mult(x, y)
unsigned int x, y;
{
    unsigned int reg = 0;

    while(y--)
        reg += x;
    return reg;
}

使用位操作,可以利用数据编码的特性。 如前所述,位移与乘以2相同。 使用此加法器可以使用2的幂。

// 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;
}

答案 2 :(得分:3)

我相信这应该是左移。 8是2 ^ 3,所以左移3位:

2&lt;&lt; 3 = 8

答案 3 :(得分:3)

你将被乘数分解为2的幂 3 * 17 = 3 *(16 + 1)= 3 * 16 + 3 * 1  ... = 0011b&lt;&lt; 4 + 0011b

答案 4 :(得分:3)

public static int multi(int x, int y){
        boolean neg = false;
        if(x < 0 && y >= 0){
            x = -x;
            neg = true;
        }
        else if(y < 0 && x >= 0){
            y = -y;
            neg = true;
        }else if( x < 0 && y < 0){
            x = -x;
            y = -y;
        }

        int res = 0;
        while(y!=0){
            if((y & 1) == 1) res += x;
            x <<= 1;
            y >>= 1;
        }
        return neg ? (-res) : res;
    }

答案 5 :(得分:0)

-(int)multiplyNumber:(int)num1 withNumber:(int)num2
{
    int mulResult =0;
    int ithBit;

    BOOL isNegativeSign = (num1<0 && num2>0) || (num1>0 && num2<0)   ;
    num1 = abs(num1);
    num2 = abs(num2);


    for(int i=0;i<sizeof(num2)*8;i++)
    {
        ithBit =  num2 & (1<<i);
        if(ithBit>0){
            mulResult +=(num1<<i);
        }

    }

    if (isNegativeSign) {
        mulResult =  ((~mulResult)+1 );
    }

    return mulResult;
}

答案 6 :(得分:0)

我刚刚意识到这与前一个答案相同。大声抱歉。

public static uint Multiply(uint a, uint b)
{
   uint c = 0;
   while(b > 0)
   {
      c += ((b & 1) > 0) ? a : 0;
      a <<= 1;
      b >>= 1;
   }
   return c;
}
相关问题