简体   繁体   English

仅使用位运算将两个数字相乘

[英]multiply two numbers using only bit operations

While learning Bit operations in c,I was searching for code to multiply two numbers using only bit operations , I found the following code!. 在学习c中的位运算时,我正在寻找仅使用位运算将两个数相乘的代码,结果发现了以下代码! I am unable to understand how ternary operator is working in the following scenario and producing the correct o/p. 我无法理解三元运算符在以下情况下如何工作并产生正确的o / p。

#include<stdio.h>
static int multiply (int x, int y) 
{
    return  y==0?0:((y&1) ==1?x:0)+multiply(x<<1,y>>1);
}
int main()
{
    printf("%d",multiply(2,3));
    return 0;
}

Can someone please explain how is the above code working?. 有人可以解释上面的代码如何工作吗?

That is not using "only bit operations", since it's using + to add numbers. 不是使用“仅位操作”,因为它是使用+加上数字。

Maybe indenting can help break up the complicated expression: 缩进也许可以帮助分解复杂的表达式:

return (y == 0 ? 0
               : (y & 1) == 1 ? x
                              : 0)
       + multiply(x << 1, y >> 1);

Basically it's a recursive addition, that stops when y reaches 0. If the least significant bit of y is set, x is added to the result, else it is not. 基本上,这是一个递归加法,在y达到0时停止。如果设置了y的最低有效位,则将x添加到结果中,否则不进行添加。 On each recursion, one bit of y is dropped so that it eventually will reach 0. The value of x is shifted to the left, very much like when doing multiplication by hand. 在每个递归的一位y被丢弃,这样最终会达到0的值x被移到左侧,用手做乘法的时候很像。

For instance if x = 3 (binary 11 ) and y = 6 (binary 110 ), it will compute 例如,如果x = 3 (二进制11 )和y = 6 (二进制110 ),它将计算

0 * 3 + 1 * 6 + 1 * 12 = 18

And of course 18 is 3 * 6. 当然18是3 * 6

Each recursion step is written as a * b where a is the least significant bit of y at that step (reading from the left, you get 0, 1, 1 which is the bits of y starting with the least significant bit) and b is the value of x at that step. 每个递归步骤都写为a * b ,其中a是该步骤中y的最低有效位(从左侧读取,您将得到0、1、1,这是y的最低有效位开始的位), b是在该步骤中x的值。

If y is odd, x * y = x + (x * 2) * (y / 2) 如果y为奇数,则x * y = x + (x * 2) * (y / 2)

If y is even, x * y = (x * 2) * (y / 2) 如果y为偶数,则x * y = (x * 2) * (y / 2)

With the logic above, and use recursion until y = 0 . 使用上述逻辑,并使用递归直到y = 0为止。

If you are struggling understanding a complex nested use of the conditional operator, then simply expand it to an if statement: 如果您在努力理解条件运算符的复杂嵌套使用,只需将其扩展为if语句:

static int multiply (int x, int y) 
{
    if (y==0)
        return 0;
    else
        return ((y&1) ==1?x:0)+multiply(x<<1,y>>1);
}

And then expand the inner conditional operator: 然后展开内部条件运算符:

static int multiply (int x, int y) 
{
    if (y == 0)
        return 0;
    else if ((y&1) == 1)
        return x + multiply(x<<1, y>>1);
    else return
        return multiply(x<<1, y>>1);
}

Once you've expanded it like this, it should be clear what the expression is doing. 像这样展开后,应该清楚表达式在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM