B Division Exceptions
B – 4
There is one case where this discrepancy does not occur. If the result of the
division operation should equal 0x8000, then it will be correctly
represented, and not be one LSB off.
There are several ways to correct for this error. Before changing any code,
however, you should determine if a one-LSB error in your quotient is a
significant problem. In some cases, the LSB is small enough to be
insignificant. If you find it necessary have exact results, two solutions are
possible.
One is to avoid division by negative numbers. If your divisor is negative,
take its absolute value and invert the sign of the quotient after division.
This will produce the correct result.
Another technique would be to check the result by multiplying the
quotient by the divisor. Compare this value with the dividend, and if they
are off by more than the value of the divisor, increase the quotient by one.
B.2.2
Unsigned Division Error
Unsigned divisions can produce erroneous results if the divisor is greater
than 0x7FFF. You should not attempt to divide two unsigned numbers if
the divisor has a one in the MSB. If it is necessary to perform a such a
division, both operands should be shifted right one bit. This will maintain
the correct orientation of operands.
Shifting both operands may result in a one LSB error in the quotient. This
can be solved by multiplying the quotient by the original (not shifted)
divisor. Subtract this value from the original dividend to calculate the
error. If the error is greater than the divisor, add one to the quotient, if it is
negative, subtract one from the quotient.
B.3
SOFTWARE SOLUTION
Each of the problems mentioned in this Appendix can be compensated for
in software. Listing 1 shows the module
divide_solution
. This code can be
used to divide two signed or unsigned numbers to produce the correct
quotient, or an error condition.
In addition to correcting the problems mentioned, this module provides a
check for division overflow and computes the remainder following the
division.