To solve this problem, the first thing you want to do is figure out how to get simple arithmetic operations using only bitwise operators.
For example, adding can be achieved using this method.
int add(int a, int b) { int c; while (a != 0) { c = b & a; b = b ^ a; c = c << 1; a = c; } return b; }
Then this is the question of doing the multiplication by adding:
int mult(int a, int b) { int i = 0; int c = 0; while (i < b) { c = add(c, a); i = add(i, 1); } return c; }
This multiplication does not work yet if b is negative, but since this seems like a home problem, I will leave this as an exercise for you.;)
Edit: Although multiplication is intuitive after adding, the add function is not so easy to understand, so I will explain it here.
Say you want to add two numbers, 11010011 and 10101. The usual way to do this is to align them like this:
11010011 + 10101
You will notice that when you add two binary numbers, if the i-th bit of both numbers is 1, then the resulting bit is 0, and the bit is transferred to the bit to the left of i.
This wrapping is what the 'c' variable holds in code.
We beat the wise and b and a get only bits where both a and b are 1, then we left a shift of 1 to get the carry bit.
Then you can see the bits where a and b are different from each other, that is, one of the bits is 1 and the other bit is 0. The resulting bit in this case will be 1 without transfer.
what this line stores:
b = b ^ a;
The line above essentially removes the bits where both a and b are 1 (they are now stored in c).
So now you have two more numbers b and c that you need to add together.
First, consider where we are, with an example after the first iteration of the loop
c = a = 00100010 b = 11000110
This may not be obvious, but b accumulates the amount received. After more iterations of the loop, more bits that are carried are βaddedβ back to b, and transfers are stored again in c. In this sense, you can think of the xor operator as adding operations without hyphenation.
Here is the second iteration of this loop:
c = a = 00000010 b = 11100100
3rd iteration:
c = a = 00000000 b = 11100110
Now c (and a) is 0, so you no longer need to add. We exit the loop and return b. Please note that even if you continue the cycle, none of the numbers will change.