I know how shr division works but it dividing just even numbers. I want to divide the number by 3. What is the assembly 8086 code of this problem? Thanks.
Asked
Active
Viewed 410 times
0
-
4You can't use a right shift alone to divide by anything but a power of 2. – Thomas Jager Mar 29 '21 at 13:24
-
1You can use `div` as an easy (but slow) way to divide by arbitrary numbers, or see https://stackoverflow.com/questions/41183935/why-does-gcc-use-multiplication-by-a-strange-number-in-implementing-integer-divi for how to do it with multiplication, similar to dratenik's answer but using `mul`. – Nate Eldredge Mar 29 '21 at 13:58
-
A faster algorithm that's inaccurate only for large numbers is also possible, see [Divide by 10 using bit shifts?](https://stackoverflow.com/q/5558492). Also, [How can I multiply and divide using only bit shifting and adding?](https://stackoverflow.com/a/32443307) shows how to use *only* shifts and add/adc (not mul with a magic constant) in a loop to do division. – Peter Cordes Mar 29 '21 at 16:17
-
A binary bit-shift by design implies a multiplication (or division) by a power of 2. For 8086 your best bet would be the `div` instruction, see https://www.sandpile.org/x86/opc_grp.htm – StarShine Mar 29 '21 at 18:24
1 Answers
2
Dividing by 3 is the same as multiplying by 1/3. 1/3 in binary is 0.010101...
So in pseudocode:
sum:=0
tmp:=IN
while (tmp>0) {
shr tmp, 2
sum += tmp
}
OUT:=sum
-
3Interesting idea, but not too accurate: from 1 to 500 this gets 19 correct answers; it is usually under by 1. – Erik Eidt Mar 29 '21 at 15:06
-
3[How can I multiply and divide using only bit shifting and adding?](https://stackoverflow.com/a/32443307) shows how to properly do exact division with just right shifting (and add/adc), for runtime-variable divisors. If you want to optimize that for a known constant 3, that might be a good starting point. – Peter Cordes Mar 29 '21 at 16:18