Category:Z80 Assembly: Difference between revisions

Content added Content deleted
m (changed tags)
(changed tags and cleaned up)
Line 66: Line 66:
Suppose you have a byte at some memory location and you want to know if it's odd or even.
Suppose you have a byte at some memory location and you want to know if it's odd or even.


<syntaxhighlight lang=z80>
If you don't need the actual value, the first choice would be:
<lang z80>BIT 0,(HL) ; 2 bytes, 12 cycles
LD A,(HL) ; 1 byte, 7 cycles
JR nz,odd</lang>

You could also do the following:
<lang z80>LD A,(HL) ; 1 byte, 7 cycles
BIT 0,A ; 2 bytes, 8 cycles
BIT 0,A ; 2 bytes, 8 cycles
JR nz,odd</lang>
JR nz,odd
</syntaxhighlight>

If you don't need the actual value, you can use:
<syntaxhighlight lang=z80>
BIT 0,(HL) ; 2 bytes, 12 cycles
JR nz,odd
</syntaxhighlight>

But there are also a few other ways to do it, which are faster and/or take fewer bytes to execute. <code>BIT 0,A</code> takes 2 bytes to encode. So does <code>AND 1</code> but it's a little faster. It does destroy the accumulator but if you don't care about that, it's better to use <code>AND 1</code>.


<syntaxhighlight lang=z80>
But there are also a few other ways to do it, which are faster and/or take fewer bytes to execute. <code>BIT 0,A</code> takes 2 bytes to encode. So does <code>AND 1</code> but it's a little faster. It does destroy the accumulator but if you don't care about that, it's better to use AND 1.
<lang z80>LD A,(HL) ; 1 byte, 7 cycles
LD A,(HL) ; 1 byte, 7 cycles
AND 1 ; 2 bytes, 7 cycles
AND 1 ; 2 bytes, 7 cycles
JR nz,odd</lang>
JR nz,odd
</syntaxhighlight>


Or is it? There's an even faster way than this that takes only ONE byte to encode:
Or is it? There's an even faster way than this that takes only ONE byte to encode:
<syntaxhighlight lang=z80>
<lang z80>LD A,(HL) ; 1 byte, 7 cycles
LD A,(HL) ; 1 byte, 7 cycles
RRCA ; 1 byte, 4 cycles
RRCA ; 1 byte, 4 cycles
JR c,odd</lang>
JR c,odd
</syntaxhighlight>


If you don't care about destroying the accumulator (i.e. you only need the result of the test and not the number being tested) then RRCA outperforms AND 1 in every way. AND 1 in this case still has its uses if you need bit 0 to reflect the result of the test. If you don't, use RRCA instead.
If you don't care about destroying the accumulator (i.e. you only need the result of the test and not the number being tested) then <code>RRCA</code> outperforms <code>AND 1</code> in every way. <code>AND 1</code> in this case still has its uses if you need bit 0 to reflect the result of the test. If you don't, use <code>RRCA</code> instead.


===Bit Shifting===
===Bit Shifting===