dividing

Jan 29, 2010 at 8:30am
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 Jan 29, 2010 at 8:30am
Jan 29, 2010 at 10:31am
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 )
Jan 29, 2010 at 1:31pm
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.
Jan 29, 2010 at 3:29pm
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.