Revs on the BBC Micro

# Maths (Arithmetic): Divide8x8

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

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), subtracting
the largest possible multiple of the divisor (V) after each shift; each bit of
A where we can subtract Q gives a 1 the answer to the division, otherwise it
gives a 0.

Arguments:

T                    This has something to do with rounding the result

A                    Unsigned integer

V                    Unsigned integer

.Divide8x8

ASL T                  \ Shift T left, which clears bit 0 of T, ready for us to
\ start building the result

\ We now repeat the following five instruction block
\ eight times, one for each bit in T

ROL A                  \ Shift A 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 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
```