Page 203 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 203
180 Chapter 7 Arithmetic Operations
7.1 Multiplication and Division
This section illustrates basic multiplication and division algorithms using the 6812
instruction set. Because there are 6812 instructions that give the same results, these
subroutines are not useful for this machine. However, for other instruction sets that do
not have multiply and divide instructions, these subroutines are the only ways to perform
multiplication and division on these machines. Finally, these subroutines provide an
understanding of how the operations can be implemented in a controller and how these
operations can be extended to higher precisions where the instructions at that level of
precision may be unavailable in the microcontroller's instruction set.
We first look at multiple-precision multiplication. The 6812 microcontroller has
several instructions that multiply 8-bit unsigned integers and 16-bit signed and unsigned
numbers. To see the advantages of the MUL instruction, look at the subroutine BINMUL
of Figure 7.1, which does exactly the same multiplication as MUL, which takes three
clock cycles. Neglecting the clock cycles for the BSR and RTS instructions, BINMUL
takes 87 to 95 clock cycles to execute the multiplication. This illustrates that generally,
hardware operations are 10 to 100 times faster than the same operations done in software.
Turning to the division of unsigned integers, the subroutine of Figure 7.2 divides
the unsigned contents of B by the unsigned contents of A, returning the quotient in B and
the remainder in A. To understand better the division subroutine of Figure 7.2, let's look
more closely at binary division, where, for simplicity, we consider just 4-bit numbers.
To divide 6 into 13, we can mimic the usual base-10 division algorithm as follows:
*
* BINMUL multiplies the two unsigned numbers in A and B, putting
* the product in D. Register Y is unchanged.
*
BINMUL: PSHA ; Save first multiplier
CLRA ; Accumulator D will become the product
LDX #8 ; Count out 8 loops
*
LOOP j CLC ; Clear carry, if not adding first number
BITB #1 ; If multiplier bit is 1
BEQ SHIFT
*
ADDA 0, SP ; Add first number
*
SHIFT: RORA ; Shift 16 bits, feeding carry back into sum
RORB
*
DBNE X, LOOP ; Count down, repeat
*
LEAS 1, SP ; Balance stack
RTS
Figure 7.1.8-Bit Unsigned Multiply Subroutine