Alex Rivera | Logout

How can I use bit shifting to replace integer division?

Asked 2010-10-03T16:55:16.440
17

I understand how to do it for powers of 2 so that's not my question.

For example, if I want to find 5% of a number using a bit shift instead of an integer divide, how would i calculate that?

So instead of (x * 20 / 19), I could do (x * 100 >> 11). Now this isn't right but it's close and I arrived at it using trial and error. How would I determine the most possible precise shift to use?

Edit
Report

1 Answer

3

You can't do everything with shifts, you will instead need to use 'magic' divisors(see hackers delight). Magic division works by multiplying a number by another suitably large number, rolling it over in such a way as to yield the answer of division(mul/imul is faster than div/idiv). There magic constants are only unique for each prime, multiples require a shift, eg: unsigned division by 3 can be represented (on 32 bit) as x * 0xAAAAAAAB, division by 6 would be (x * 0xAAAAAAAB) >> 1 division by 12 would shift by 2, 24 by 3 etc (its the geometric series 3 * (2 ^ x), where 0 <= x < 32)

answered 2010-10-03T20:22:38.050

Your Answer