Machine Code — CP Branching Tests

Author(s): Jonathan Bobst
Publication: Syntax
Pub Details: Syntax/Syntax ZX80 v3 n8 (Volume 3, Issue 8)
Date: August 1982
Pages: 8

CPs are 1-3 byte codes that compare two numbers. More exactly, they subtract the number you are looking for from what has been loaded into the Accumulator. The general method of using CPs is to set up a loop that will “peek” into a block of addresses serially, or one after another.

For instance, suppose you have a block of data in REM addresses and you want to return to BASIC at the last piece of data:

1. Choose a number that is not valid data, say 23, and store it in the last data address in the block.

2. Initialize a register pair as a “data pointer” with an INCrement instruction. Load A with the contents of the address pointed to. (LD A,(BC) for example, where BC holds the current data address and is stored on the stack.)

3. Compare the new data to “23” (CPn, where n=23).

4. If the data is 23, the Z flag is set for a test so you can branch (either to BASIC or to reset the pointer). If the data is not 23, A still contains valid data (only the Flags are affected), the branch-test (RET Z, JR Z, etc.) fails, and the data can be processed.

CPs are simple to use if you understand two things: A must be loaded with “unknown” data from an address, and you must follow the CP with a test-and-branch depending on which Flag you test (JR C, CALL PO, nn, RET NZ, JP M,nn, for example).

In addition to CPs, the Z80 also has a few instructions that actively search and test data automatically. With these, however, you must load-initialize HL with the data address and load BC with the number of addresses to search (iterations of the automatic loop).

Next: TESTING BITS FOR BRANCHING