[A83] Re: 1 byte division routine
[Prev][Next][Index][Thread]
[A83] Re: 1 byte division routine
In general, I don't think there can be such a thing as a fast division
routine on the z80 simply because the processor doesn't support such a
thing.
The "standard" way of doing integer division (which is in the ROM routine
for doing so) divides a 16-bit value by an 8-bit value in between 710 and
748 clock cycles (I didn't count very carefully, but I think this is
right) depending on the data. It is not very long or very complicated,
and I doubt a much better result could be obtained without unrolling the
loop or using large tables.
For dividing on byte by one byte, I would suggest something like this,
which uses a similar method:
; divides H by C, leaving result in H, remainder in A
xor a ; 4 cycles
ld b,8 ; 7 cycles
loop:
sla h ; 8 cycles (64 total)
rla ; 4 cycles (32 total)
cp c ; 4 cycles (32 total)
jr c,no ; 12/7 cycles (96/56 total)
sub c ; 0/4 cycles (0/32 total)
inc h ; 0/4 cycles (0/32 total)
no:
djnz loop ; 13/8 cycles (99 total)
I didn't actually test this, but I think it is at least close to being
right. This should take something like 334 to 358 cycles depending on the
data. Anyone out there is welcome to try to prove me wrong, but I think
this is about as fast as it is going to get on a processor like the Z80
without unrolling the loop (which could save 106 cycles) or using a table
(which could save a lot more; if you were only going to divide by one
of a few values, you could just put all the results in tables).
This will only work for unsigned values; if you want to do signed math, it
is probably easiest just to check the signs at the start, take the
absolute values of everything, then negate the result if appropriate.
Follow-Ups: