Multiplication of two integers using bitwise operators

前端 未结 7 1036
迷失自我
迷失自我 2020-11-30 00:49

How can I multipy two integers using bitwise operators?

I found an implementation here. Is there a better way of implementing multiplication?

For example: 2

7条回答
  •  忘掉有多难
    2020-11-30 01:16

        #include
        void main()
        {
            int n, m, i, j, x, large, small, t1, m2, result, a1, a2, a3, c, c1, c2, r, r1, la, re;
    
            printf("Enter two numbers\n");
            scanf("%d%d", &n, &m);
            result = 0;
    
            if (n > m)
            {
                large = n;
                small = m;
            }
            else
            {
                large = m;
                small = n;
            }
    
            c = 0;
    
            while (small)
            {
                t1 = small;
                t1 &= 1;
    
                if (t1 == 1)
                {
                    printf("\n %d", large);
                    la = large;
                    re = result;
                    m2 = 0;
                    r1 = 1;
                    while (re || la || c)
                    {
                        a2 = la;
                        a2 &= 1;
                        a3 = re;
                        a3 &= 1;
    
                        c1 = a2 & a3;
                        r = a3 ^ a2;
    
                        c2 =r & c;
                        r ^= c;
                        if (c1 || c2)
                            c = 1;
                        else
                            c = 0;
    
                        result &= ~r1;
                        x = r;
                        m2 >>= 1;
                        while (m2)
                        {
                            r <<= 1;
                            m2 >>= 1;
                        }
    
                        result |= r;
                        la >>= 1;
                        re >>= 1;
                        r1 <<= 1;
                        m2 = r1;
                    }
    
                }
                large <<= 1;
                small >>= 1;
    
            }
            printf("\n%dX%d= %d\n", n, m, result);
        }
    

提交回复
热议问题