Category:Z80 Assembly: Difference between revisions

Line 54:
Suppose you have a byte at some memory location and you want to know if it's odd or even.
 
If you don't need the actual value, the first choice would be:
You could do the following:
<lang z80>LDBIT A0,(HL) ; 2 bytes, 12 cycles
JR nz,Oddodd</lang>
BIT 0,A
JR nz,Odd</lang>
 
You could also do the following:
But there's 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
BIT 0,A ; 2 bytes, 8 cycles
AND 1
JR nz,Oddodd</lang>
 
But there's 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
AND 1 ; 2 bytes, 7 cycles
JR nz,odd</lang>
 
Or is it? There's an even faster way than this that takes only ONE byte to encode:
<lang z80>LD A,(HL) ; 1 byte, 7 cycles
RRCA ; 1 byte, 4 cycles
RRCA
JR c,Oddodd</lang>
 
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.
 
===Bit Shifting===
The Z80 does have bit shifting, but thanks to RLCA and RRCA it's often faster to rotate instead. Compare the following two code snippets: