gp2000
Experienced Member
A classic trick on the Z-80 to save a little bit of time and space is to use one of these instead of "LD A,0"
A very good replacement as long as alteration of the flags is not a problem.
However, in the name of robustness, a more modern "Trust, but verify" technique is preferred.
While heeding Knuth's words ("... premature optimization is the root of all evil (or at least most of it) in programming") it seems fair to optimize that approach a bit.
On the other hand a Monte Carlo approach may be called for.
Ah, but those familiar with the Z-80 will have spotted a bug. The top bit of R register only changes when loaded. Easily fixed by elegantly mixing in the deterministic approach:
Should flag register changes be a concern we can borrow a technique from the MIPS processor which forces one of its registers to always be a zero value. After brief consideration, C is the obvious choice.
While C may be needed for the odd LDIR this is no problem as it will be 0 after it executes. Now a quick
will do the TRICK. And it generalizes to all the other 8 bit registers. I hope these ideas will help improve your Z-80 programs. Have a nice DAY.
Code:
XOR A
SUB A
A very good replacement as long as alteration of the flags is not a problem.
However, in the name of robustness, a more modern "Trust, but verify" technique is preferred.
Code:
TOZ: DEC A
JR NZ,TOZ
While heeding Knuth's words ("... premature optimization is the root of all evil (or at least most of it) in programming") it seems fair to optimize that approach a bit.
Code:
TOZ: ADD A,A
JR NZ,TOZ
On the other hand a Monte Carlo approach may be called for.
Code:
TOZ: LD A,R
JR NZ,TOZ
Ah, but those familiar with the Z-80 will have spotted a bug. The top bit of R register only changes when loaded. Easily fixed by elegantly mixing in the deterministic approach:
Code:
TOZ: LD A,R
ADD A,A
JR NZ,TOZ
Should flag register changes be a concern we can borrow a technique from the MIPS processor which forces one of its registers to always be a zero value. After brief consideration, C is the obvious choice.
- HL is too important addressing memory and doing 16 bit stuff.
- DE is HL's understudy, ready to take over at a moment's notice (and an EX DE,HL).
- DJNZ rules out B.
- C pretty much looks like a 0 already.
While C may be needed for the odd LDIR this is no problem as it will be 0 after it executes. Now a quick
Code:
LD A,C
will do the TRICK. And it generalizes to all the other 8 bit registers. I hope these ideas will help improve your Z-80 programs. Have a nice DAY.