Basil’s Compendium: Addition, Overflow, Carry

Author(s): John (Basil) Wentworth
Publication: SyncWare News
Pub Details: SyncWare News v4 n1 (Volume 4, Issue 1)
Date: Sept-Oct 1986
Pages: 13-16

This chapter will show you how to add and subtract, and how to “increment” and “decrement” registers; it will tell you about overflow and carrying; and it will introduce the concept of flags.

But before we go on, I remember that I left you last time with a computer full of mega-REM, with the promise that I’d show you what to do with it. OK, here you are.

First generate, as line 2, a mega-REM of exactly 704 nulls, plus the ” at the end. You can count the number of nulls by PRINT USR 16517. Next, key in another line:

9 STOP

and leave that line there for the rest of your life, to protect the top of the mega-REM. Now edit line 2 so that it reads

2 PRINT "..........(etc)

It will take a very long time for such a long line to come down into the EDIT position, but have patience. Check the length of the mega-REM once more by RUNning the program. You should get a screen full of dots, with a report code of 9/9, showing that the program hit the STOP at line 9. If you have miscounted, and the screen is not full, you can add extra dots to eke out the display. If the report code is 5/2, indicating that the screen has overflowed, then you have too many dots, and should remove a few. Any other report code means that you are in trouble, and better start over. But let’s assume that it came out right.

16514 42  E      LD HL,
16515 12 £ (16396)
16516 64 RND
16517 35 7 INC HL
16518 17 ) LD DE,
16519 156 ▒ 16540
16520 64 RND
16521 62 Y LD A,
16522 22 - 22
16523 1 ▒ LD BC,
16524 32 4 32
16525 0
16526 237 GOSUB LDIR
16527 176 ▒
16528 35 7 INC HL
16529 61 X DEC A
16530 32 4 JR NZ,
16531 247 RUN -9
16532 201 TAN RET

FIG 9-1. SCREEN STORAGE PROGRAM

Now use your loading technique to build a 1 REM line like that shown in Figure 9-1, and you’re ready to go. Put in a program like

1000 PRINT AT 10,3;"BASIL LOVES JOCELYN"
1010 RAND USR 16514

and GOTO 1000. You should find that your words are immortalized in line 2, and that RUNning the program will bring them back to the screen just as you had them. Any other display can be frozen in the same way, with a couple of limitations:

1. The display may not contain any quotation marks. Even though you carefully use the required “”, the computer will store it as a “, with the result that any attempt to PRINT will result in a crash.

2. The USR 16514 command has to be a part of the program that generates the display. If you generate the display separately, and then try to USR it (if you’ll pardon my so cavalierly using USR as a verb), the screen will be cleared when you enter the USR command, and you’ll find that you have saved a screen full of nothing. A perfectly symmetrical display, but not a particularly useful one.

NOTE: It’s possible to use a machine code routine to transfer the REM statement into the PRINT area of the computer (essentially a reverse of what you did to put it into the REM statement). However, this is what I call sending a man to do a boy’s job.

Addition

And now back to lessons. Now that we can put numbers into the computer, move things around inside, and persuade it to tell us the value of BC, let’s see if we can find out how to make it do something “useful”.

Like addition, for instance.

Register A and register pair HL are the workhorses of the Z80 chip. You’ll find that they can do many things that the other registers can’t cope with. In fact, these registers are so important that they have been given “significant” names. “HL”, as you remember, stands for “high-low”. And “A” stands for “accumulator”.

“Accumulator” is an unfortunately ambiguous word. Besides being a bear to spell, it means many things to many people. To the British, for instance, the accumulator is a storage battery. To the physicist, it can be a device that stores an electric charge. To us, it means something that accumulates data. But all the other registers accumulate data, too. They just weren’t around when this one was named.

I think it’s safer to use the term “register A”, and to remember that this register will do things that some others can’t. But be prepared to recognize the term “accumulator” when you see it.

 62  LD A,
2 2
198 ADD A,
2 2
201 RET

FIGURE 9-2. ADDING WITH
REGISTER A
                       →   A   B   C   D   E   H   L   N  (HL)
ADD TO A  (ADD A,)→       135 128 129 130 131 132 133 198 134
ADD WITH CARRY
    TO A (ADC A,)→        143 136 137 138 139 140 141 206 142
SUBTRACT FROM A
         (SUB A,)→        151 144 145 146 147 148 149 214 150
SUBTRACT WITH CARRY
  FROM A (SBC A,)→        159 152 153 154 155 156 157 222 158
COMPARE WITH A
          (CP A,)→        191 184 185 186 187 188 189 254 190

TABLE 9-1.  INSTRUCTIONS FOR REGISTER A
             →    BC    DE    HL    SP
ADD HL,→           9    25    41    57
ADC HL,→         *74   *90  *106  *122
SBC HL,→         *66   *82   *98  *114

*  INDICATES PRECEDED BY 237

TABLE 9-2.  INSTRUCTIONS FOR
            REGISTER HL

The instructions for adding to and subtracting from A and HL are given in Tables 9-1 and 9-2. For the time being, don’t worry about the other instructions and registers that you see mentioned there.

Let’s start in with the classic addition problem of 2+2. Try the routine given in Figure 9-2. Put the routine into the computer, and PRINT USR 16514. What do you get?

 62  LD A,
2 2
198 ADD A,
2 2
79 LD C,A
6 LD B,
0 0
201 RET

FIGURE 9-3. ADDING WITH
REGISTER A (CORRECTED)

Well, what did you expect? Register A has (probably) arrived at the correct value, but you told the computer to give you the present contents of register pair BC. (If you caught this one on the way by, congratulations!) We’ll have to shift the data from A to BC before we can look at it.

How? LET C=A, and LET B=0. (Why not LET B=A and LET C=0?) So our complete program is as shown in Figure 9-3.

Try it. Do you get 4?

Overflow

Now, just for fun, try a number that’s too big for the register to handle. Use the program in Figure 9-3 to add 2 to 255. Remember that 255 is the biggest number that the A register (or any single byte anywhere) can handle. And the sum that we’ve set for it comes to 257.

Well, what is the logical thing for the computer to do? It could give up, of course. Or it could start over–it could say 0 for 256, 1 for 257, and so on. RUN the program, and verify that this is indeed what it does. Try adding 255 to other numbers. H’mm–it begins to look as if adding 255 is the same as subtracting 1. So adding 254 would be like subtracting 2, right? Try it and see. Tuck this fact away in your mind–we’ll find a use for it later.

Now how about 2-register numbers? Let’s try the same sequence, using the HL register. First, 2+2 (Figure 9-4). Print USR 16514. There’s that 4 that you expected. Try adding 2+255, and see if you can get 257 that way. Sure, the two bytes together handle this problem easily.

Let’s see what happens when you exceed the capacity of the pair (which is 65535, you will remember). Load the HL register with 65535 (255 in one byte, 255 in the other). Add 1 to it. Do you get 0 again? Now add 65535 to 4, and see if you get 3.

Now subtract. Let’s go through a similar set of exercises. Follow Figure 9-5. There’s 4-2=2. Try other combinations, like 5-2, 6-4, 8-3. Try 5-6. And there’s that 255 again, standing in for -1. Subtract 255 from 6. As you would expect, you get 7. The 255 still thinks it’s a -1. Hold onto that thought. It’ll come in handy when we get to the chapter on GOTO.

 33  LD HL,
2 2
0 *
17 LD DE, **
2 2
0 *
25 ADD HL,DE
68 LD B,H
77 LD C,L
201 RET

* TWO BYTES OF DATA NEEDED; LSN
FIRST

** THERE IS NO DIRECT WAY OF
ADDING A NUMBER TO HL

FIGURE 9-4. ADDING WITH
REGISTER PAIR HL

And for double-register numbers. Try the sequence in Figure 9-6.

HEY! There isn’t any instruction for subtracting a two-byte number. But there’s something that looks a little like it–Subtract With Carry (SBC). Try it. Notice that it takes a two-byte instruction: 237 followed by 82. You’ll find several of these two-byters, with 237 or 203 as the first of the two bytes. (And a whole couple of ‘nother sets beginning with 221 and 253.) Think of the first of the two bytes as a sort of SHIFT key, that gives a new meaning to the following byte.

 62  LD A,
4 4
214 SUB A,
2 2
79 LD C,A
6 LD B,
0 0
201 RET

FIGURE 9-5. SUBTRACTING WITH
REGISTER A
 33  LD HL,
4 4
0 0
17 LD DE,
2 2
0 0
- SUB HL,DE

FIGURE 9-6. SUBTRACTING WITH
REGISTER PAIR HL

We won’t be using the 203 series for a long time. That little giant is way beyond the scope of our present knowledge. And the 221 and 253 won’t come along for some time, either. But we’re going to call on members of the 237 set again and again.

Let’s continue with the problem given in Figure 9-7. So 4-2 is still 2. Try 4-5, and see whether you get 65535, which is the 256-imal way of saying -1.

But what does this Subtract With Carry mean?

237  SBC HL,DE
82
68 LD B,H
77 LD C,L
201 RET

FIGURE 9-7. COMPLETION OF
FIG. 9-6

Carry

Use the program of Figure 9-7 once more to prove that 4-2 is still equal to 2. Now enter the following bytes at the beginning of the program, before the 33. As always, be sure that you have enough nulls in the 1 REM statement to accommodate the whole program.

 62  LD A,
2 2
214 SUB A,
3 3

Use PRINT USR 16514. What’s this? Does 4-2=1 all of a sudden? Try PRINT USR 16518 instead of 16514, to avoid those first four bytes. Now it comes out 2, just as it should.

We learn a number of lessons from this exercise:

1. The main lesson is that SBC (Subtract With Carry) takes into account the recent history of the computer. If you’ll notice, those first four bytes have the effect of subtracting 3 from 2, which leaves a negative answer. To let us know that the result of that operation is outside the computer’s normal range, the Z80 has “SET a carry flag”, as the experts like to put it. Properly speaking, I suppose that the “carry” should be called a “borrow” in this case, but the same flag would have been SET if the first operation had been, say, LD A,255; ADD A,3; giving a true carry. (Try it.)

The carry flag is a perishable signal–if you don’t use the information right after the flag is SET, you may be too late. You may find that a subsequent computer operation has RESET it (canceled it) in the meantime.

Add With Carry (ADC) works very much the same way. If the Carry flag is SET, then ADC will add an extra 1 to the sum it generates. Again, try it out. And try ADC and SBC with register HL. Remember, you have to load HL with two bytes of data, LSN first, and you have to LD B,H and LD C,L in order to read out the contents of HL.

It doesn’t matter a whit whether or not the action that SET the Carry flag was relevant to the rest of the program. How is the computer to know what is relevant and what isn’t? Considerations like that are the responsibility of you, the programmer. All the computer cares is whether the flag is SET–never mind how it got that way.

To sum up, if the Carry flag is SET, a Subtract With Carry (SBC) will subtract 1 from the result, while an Add With Carry (ADC) will add 1 to the sum. If the instruction is Add or Subtract (without carry), then the condition of the Carry flag doesn’t matter. And, of course, the computer will then SET or RESET the Carry flag, according to the results of the operation. And again, to reflect the next operation. And again…and again…

The incidental lessons from this exercise are:

2. You can drop in on a program in the middle, as long as the entry point makes sense. If it doesn’t make sense, then the results will be meaningless–if indeed the program doesn’t crash. You’ll notice that when we started the program at 16518, the computer ignored those first four bytes, and zipped through the program as if they didn’t exist.

This suggests some interesting possibilities to the adventurous mind. Like–why not put two or three (or more) programs into the same REM statement, and let your USR number signal which segment you want at any given moment? No sweat. You can even arrange it so several programs share parts of the machine code. In fact, this is what the ROM in your computer does.

Or why not start the code with an operation that will be performed in some cases, but not in others? And rely on your BASIC program to enter the machine code routine at the proper point. Sure, you can do that. In fact, you just did.

Or–really wild–why not include some plain language in the REM line, as sort of a REM in itself? Like starting your REM statement:

1 REM LINE RENUMBER.. (followed by the machine code CHR$s)

Your USR number, then, would be chosen so that the computer skips the plain language and starts at the beginning of the machine code. Or you could put the plain language at the end of the machine code sequence. In either case, you could tell at a glance what this particular segment of machine code was designed to do.

3. The other lesson is that, once you return to BASIC, the program doesn’t remember what it did the last time you ran it. It so happens that this program left the Carry flag RESET, but the computer won’t remember that next time. Nor will it remember what numbers were stored in the various registers.

The condition of the Carry flag is stored in another register that I haven’t told you about yet–the F register. F for Flags. We won’t be using this register as a register, except in a very limited sense; but we will use, time and again, the information that it stores. Other flags that are recorded in this register are Zero (was the result of the last operation zero?), Minus (was the result less than zero?), and a number of others that we won’t get around to using for many moons.

  1  LD BC,
3 3
0
3 INC BC
201 RET

FIGURE 9-8. INCREMENT

INC & DEC

There are two special cases of addition and subtraction. One of them, INCREMENT (mnemonic: INC), increases the contents of the designated register by 1. You can see how it works with the program of Figure 9-8. The output should be 3+1=4.

  1  LD BC,
3 3
11 DEC BC
201 RET

FIGURE 9-9. DECREMENT
       INC   DEC
A       60    61
B        4     5
C       12    13
D       20    21
E       28    29
H       36    37
L       44    45
BC       3    11
DE      19    27
HL      35    43
SP      51    59
(HL)    52    53

TABLE 9-3.  INC AND DEC

The opposite of INCREMENT is–no, not excrement, but DECREMENT (mnemonic: DEC). Use the program of Figure 9-9 to demonstrate that 3 decreased by 1 is 2.

The instructions for INC and DEC are given in Table 9-3.

And that’s the end of a rather lengthy lesson. There will be more.