While looking at the code in C for division/multiplication by 2, it is found that shift operator is used rather than division operator. What is the advantage of using shift over division operator?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Multiplication is complex typically... unless one of the multiplicands is the base the numbers are in themselves.
When working with base 10 math, multiplying by 10 is trivial: "append the same number of zeros as the 10 has".
This is very easy for us. The exact same rule exists in binary.
For a system already working with bits (ANDs and ORs), operations such as shift and roll already exist as part of the standard tool set. It just happens that translating
If we are doing something that isn't a power of 2 in binary, we've got to go back to the old fashioned multiply and add. Granted, binary is a bit 'easier', but a bit more tedious at the same time.
You can see, we're still doing shifts, and adds. But lets change that to
By just skipping to that last step, we have drastically simplified the entire problem without adding lots of 0s that are still 0s.
Dividing is the same thing as multiplying, just the reverse. Just as
Using the example of
You can see the steps in the long way of doing long division for binary is again quite tedious, and for a power of two, you can just skip to the answer by in effect, canceling the zeros.
(as a side note, if this is an interesting area for you, you may find browsing the binary tag on Math.SE, well... interesting.)
This a specific optimization that is made in the case that the programmer knows the divisor will be a power of 2.
If the divisor is anything but a power of 2, then this optimization is not possible and code must be rewritten to use regular division.
So, for example, if we have a function that is
We had better hope that our magic number of weekend days never becomes something other than a power of two because then we need to rewrite and unit test the function all over again.
If you write
you have to trust the compiler for optimizing it to a "shift" operation on the machine code level (which is typically faster that a general division instruction). And about 25 years ago, when I started working with C compilers, you could not be sure that the compiler worked like this. Today, any decent C compiler knows how to optimize this (at least, when you don't disable the optimizer).
If, however, you write
you can be (almost) sure that the compiler generates a shift operation, if you activate the optimizer or not.