Prev: 41745 Up: Map Next: 41886
41849: Divide
Used by the routine at DrawLine.
Divides a number by another and returns the answer as a fraction of 256 which is a number between 0 and 255 as long as the first number is the smaller. The answer is worked out one bit at a time (long division), with the answer in the shadow registers and the working in the normal registers. DrawLine uses it to work out how far to move across or up for every pixel moved in the other direction.
Input
H The number to divide (the numerator)
DE The number to divide by (the denominator)
Output
DE The remainder
HL The answer (the numerator * 256 / the denominator)
Divide 41849 LD L,H Move the numerator into L.
41850 LD H,0 H=0 (so that HL is the numerator).
41852 EXX Switch to the shadow registers.
41853 LD HL,0 HL'=0 (the answer so far).
41856 LD B,8 B'=8 (the number of bits to work out).
Divide_Loop 41858 EXX Switch to the normal registers.
41859 SLA L Shift HL left by one.
41861 RL H Rotate the carry into H.
41863 PUSH HL Stash the working number on the stack.
41864 AND A Subtract the denominator.
41865 SBC HL,DE
41867 JR C,Divide_Restore Jump to Divide_Restore if it is bigger than the working number.
41869 POP AF Discard the stashed working number, as the subtraction can stay.
41870 EXX Switch to the shadow registers.
41871 ADD HL,HL Shift the answer left by one.
41872 INC HL Add one to the answer for this bit.
Divide_Next 41873 DJNZ Divide_Loop Decrease the bit counter by one and loop back to Divide_Loop until all eight bits of the answer have been worked out.
41875 PUSH HL Stash the answer on the stack.
41876 EXX Switch to the normal registers.
41877 LD E,L E=L (the low byte of the remainder).
41878 LD D,H D=H (the high byte of the remainder).
41879 POP HL Fetch the answer.
41880 RET Return.
Divide_Restore 41881 POP HL Restore the working number from the stack.
41882 EXX Switch to the shadow registers.
41883 ADD HL,HL Shift the answer left by one.
41884 JR Divide_Next Jump to Divide_Next to move on to the next bit.
View the equivalent code in;
Prev: 41745 Up: Map Next: 41886