Sometimes we need to write code that should be very fast. Normally multiply/divide instructions are not so fast in C as compared to plus/minus instruction.
Today, we will learn to do write code for multiplication of 2 digits without using multiply instruction.
Before moving ahead, lets revise the Left shift and right shift instructions.
In C, left shift instruction is used to multiply any number by 2. e.g. if we want to multiply x by 2 then we can simply writex = x << 1;
The above line of code will multiply the value of x by 2. If we left shift by 2 then the value of x will be multiplied by 4 and so on.
Similarly, to divide any number by 2 we can right shift the number by 1 place as shown belowx = x >> 1;
Multiply number by 2:
To multiply any number by 2 we can simply right shift the number by 1 place i.e. x = x << 1;
Multiply number by 3:
To multiply any number by 3 we can simply right shift the number by 1 place and then add it to itself i.e. x = x + (x << 1);
Multiply number by 4:
To multiply any number by 4 we can simply right shift the number by 2 places i.e. x = x << 2;
Multiply number by 5:
To multiply any number by 5 we can simply right shift the number by 2 place and then add it to itself
i.e. x = x + (x << 2);
So, by using this simple trick we can speed up the code processing. You can try yourself the operation of divide by using right shift operation.