dividing

Hello,

I want to know why programmers sometime use for example:

X = (variable * 21845) << 16.

instead of:

X = variable / 3

I know that (21845 / 2^16 = 1/3), but i don't understand why you use it.

Thanks
Last edited on
Some people believe that multiplication and bit shifting is faster than division.
It may be true but this kind of tricks should be left to the compiler optimization, if you have to divide by three,
use / 3 ( or / 3.0 for floating point division )
Sometimes bit shifts are faster, but like Bazzy said; a good compiler will optimize that for you. Sometimes bit shifts are slower, but a compiler probably won't optimize it for you.
For the sake of correctness, your example should rather be:

X = (variable * 21845) >> 16

(i.e. right shift, not left)
Topic archived. No new replies allowed.