Division by a constant using shifts and adds/subtracts

后端 未结 3 1270
悲哀的现实
悲哀的现实 2020-12-17 05:36

Hi all I\'m trying to divide by an unsigned constant using only shifts and adds/subtracts - I have no problem with this if it were multiplication, but I\'m a bit stumped by

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 06:28

    I would look at the hackers delight book for this sort of thing. I dont have my copy with me, but independent of that if you look at your divisor 192, that is 0xC0, so you can divide the top and bottom by 0x40, shift 8000>>6 = 125. 8000/192 -> 125/3, but then you have to do that divide by 3. We know the answer will be somewhere between 125/2 and 125/4. With these specific numbers 125 is 0x7d or b1111101 which is 3 times b100000 + 11101 which is (3 times 0x20) + (3 times 8) + 5 so 125/3 = 0x20 + 0x8 + (5/3) and 5/3 is quickly determined as more than 1 but less than 2 so 0x28+1 = 41. Only continues to reduce with shifts if the divisor bit pattern keeps showing up on the upper bits of the numerator bit pattern. I dont know what the hackers delight or other similar sources say about the matter, I just happened to notice this pattern for these specific numbers.

提交回复
热议问题