Skip to navigation

Maths (Arithmetic): Divide16x16

Name: Divide16x16 [Show more] Type: Subroutine Category: Maths (Arithmetic) Summary: Calculate T = 256 * (A T) / (V 0)
Context: See this subroutine in context in the source code References: This subroutine is called as follows: * GetObjPitchAngle calls Divide16x16 * GetObjYawAngle (Part 2 of 4) calls Divide16x16 * GetObjYawAngle (Part 4 of 4) calls Divide16x16

In the same way that shift-and-add implements a binary version of the manual long multiplication process, shift-and-subtract implements long division. We shift bits out of the left end of the number being divided (A T), subtracting the largest possible multiple of the divisor (V 0) after each shift; each bit of (A T) where we can subtract Q gives a 1 the answer to the division, otherwise it gives a 0.
Arguments: (A T) Unsigned integer (V 0) Unsigned integer
.Divide16x16 ASL T \ Shift T left, which clears bit 0 of T, ready for us to \ start building the result in T at the same time as we \ shift the low byte of (A T) out to the left \ We now repeat the following seven-instruction block \ eight times, one for each bit in T ROL A \ Shift the high byte of (A T) to the left to extract \ the next bit from the number being divided BCS P%+6 \ If we just shifted a 1 out of A, skip the next two \ instructions and jump straight to the subtraction CMP V \ If A < V skip the following two instructions with the BCC P%+5 \ C flag clear, so we shift a 0 into the result in T SBC V \ A >= V, so set A = A - V and set the C flag so we SEC \ shift a 1 into the result in T ROL T \ Shift the result in T to the left, pulling the C flag \ into bit 0 ROL A \ Repeat the shift-and-subtract loop for bit 1 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 2 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 3 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 4 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 5 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 6 BCS P%+6 CMP V BCC P%+5 SBC V SEC ROL T ROL A \ Repeat the shift-and-subtract loop for bit 7, but BCS P%+4 \ without the subtraction, as we don't need to keep CMP V \ calculating A once its top bit has been extracted ROL T RTS \ Return from the subroutine