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

Jam*_*sev 22 bit-manipulation multiplication

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

0*8 = 0

1*8 = 8

2*8 = 16 

3*8 = 24 

4*8 = 32
Run Code Online (Sandbox Code Playgroud)

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

Pre*_*gha 39

为了将任何值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
Run Code Online (Sandbox Code Playgroud)

等等..

将位移到右侧.

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

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

therefore: x * 17 = (x * 16) + x in other words 17 x's  
Run Code Online (Sandbox Code Playgroud)

因此,要乘以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)
Run Code Online (Sandbox Code Playgroud)

即.

    0011 0000  (48)  
+   0000 0011   (3)
=============
    0011 0011  (51)
Run Code Online (Sandbox Code Playgroud)

编辑:更新到原始答案.查尔斯·佩佐尔德(Charles Petzold)写了一本很棒的书"代码",它将以最简单的方式解释所有这些内容.我完全推荐这个.


小智 10

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

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

    while(y--)
        reg += x;
    return reg;
}
Run Code Online (Sandbox Code Playgroud)

使用位操作,可以利用数据编码的特性.如前所述,位移与乘以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;
}
Run Code Online (Sandbox Code Playgroud)