Another well known bitwise trick is that you can do multiplication and division by powers of two "2^n", with just simple shifts by "n".
x = x << 2;
Read full article from Trash Can of Code: Fast Multiplication and Division
x = x << 2;
x = x >> 2;
Unlike the modulus optimization trick, the multiplication trick does work for both signed and unsigned variables, so the compiler is safe to optimize these cases for you.
In the case of the division trick there is a problem that may happen if you have a negative signed number. If you divide a negative integer and the result should have a remainder, then using shifts may give you the wrong result (for example, -1/2 should be 0, but -1>>1 is -1).
Compilers are able to optimize signed division by powers of two using shifts and interesting logic to account for the possible errors.
For the reason that compilers will make the necessary optimizations for you, it is generally better to leave the code as normal multiplications and divisions for readability and to prevent mistakes.
No comments:
Post a Comment