Simulated 16-bit Addition
z80 » Intermediate
Have you ever wanted to add an 8-bit register to a 16-bit register? You've probably
just ran the following code to add
- ld b,0 ;2 bytes 7 cycles
- ld c,a ;1 byte 4 cycles
- add hl,bc ;1 byte 11 cycles ;4 bytes 22 cycles (totals)
I wrote the opcode information to the right of each of those instructions for clock cycles and size. At the bottom I totalled the information so we can compare it with a new way of adding 8-bit registers to 16-bit ones totalled later on.
The faster way to do this is the following code using the carry flag.
- add a,l ;1 byte 4 cycles
- ld l,a ;1 byte 4 cycles
- adc a,h ;1 byte 4 cycles
- sub l ;1 byte 4 cycles
- ld h,a ;1 byte 4 cycles ;5 bytes 20 cycles (totals)
|1||Add the Least Significant Byte (LSB)
|2||Store the result in the LSB of |
|3||Add the result again into |
|4||Subtract the original result (what's now in
|5||Put that final result of the Most Significant
Byte (MSB) into |
hl = hl + a
Our final routine saves us 2 clock cycles at a cost of 1 byte extra. In programs where speed is of the escence, this routine is a must compared to the original method.
More from z80 » Intermediate
All the Flags // Debugging // Down-Left Bug // _GetKey Codes // Logical Operators // Memory, ROM, RAM, and Safe Areas // Miscellaneous Instructions // PC and SP // Random Numbers // TI's ROM Calls // Restart Commands // Simulated 16-bit Addition // The Stack // Tables and Arrays // Text Display // Variables