Multiplication of two integers using bitwise operators

前端 未结 7 1034
迷失自我
迷失自我 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:17

    This one is purely with bit-wise operations.

    public int bitwiseMultiply(int a, int b) {
        if (a ==0  || b == 0) {
            return 0;
        }
    
        if (a == 1) {
            return b;
        }
        else
            if (b == 1) {
                return a;
            }
    
    
        int result = 0; // Not needed, just for test
        int initA = a;
        boolean isORNeeded = false;
        while (b != 0 ) {
    
            if (b == 1) {
                break;
            }
    
            if ((b & 1) == 1) { // Carry needed, odd number
                result += initA; // Test, not needed
                isORNeeded = true;
            }
    
            a <<= 1; // Double the a
            b >>= 1; // Half the b
            System.out.println("a=["+a+"], b=["+b+"], result=["+result+"]");
        }
    
        return (isORNeeded ? (a | initA) : a); // a + result;
    }
    

提交回复
热议问题