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