Bit by Bit

See all articles from SYNC v4 n1
Author(s): Harry Doakes
Publication: SYNC
Pub Details: SYNC v4 n1 (Volume 4, Issue 1)
Date: January/February 1984
Pages: 56-63

When we use numbers in a computer, we usually think about them as whole numbers. Generally we do not think of them as bytes, and we certainly do not think about the fact that everything in the computer is ultimately a bunch of bits.

This time we will take a look at bits—the smallest pieces of information a computer can handle—and how the Z80 processor in your ZX/TS computer can manipulate them. You may never need most of these instructions, but it is a good idea to know something about them anyway. Then we will do something very different—we will look at how to use the Zilog Z80 CPU Programmer’s Reference Guide.

Bit Wise

What is a bit?

Bit is one of the oldest pieces of computer jargon. It is short for “binary digit”—just the first and last letters, pushed together. A digit is one of the numerals that make up a number. The value of a number depends on what the digits are, and what position each digit is in. Binary means the number is in base 2. In base 10—the decimal counting system we normally use—we have 10 different digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. In base 2, we have only 2 different digits: 0 and 1. Thus, the first few numbers in binary look like this: 1, 10, 11, 100, 101, 110, 111, and 1000.

We already know that a regular Z80 register or a single byte of memory can hold a number from 0 to 255 decimal. In base 2, that is between 0 and 11111111. Notice that the number 11111111 is 8 binary digits long. The Z80 is called an 8-bit processor because the largest value its regular registers can hold is 8 bits long.

Your manual has a chapter on counting in both binary and hexadecimal, and why these number systems are important to understand when you are programming a computer.

One Bit at a Time

Up until now we have mainly dealt with numbers in the computer the way we see them, i.e., as whole numbers.

But the computer sees numbers differently. Every number stored in the computer—in ROM, RAM, or a register—is just 8 bits to the computer. Think about that a moment. It is important. Since the computer sees each number just as a string of bits, there is no reason it cannot look at, or even change, just one bit of a number, leaving the other 7 bits alone.

In fact, the Z80 processor does so by using the instructions test, set, and reset.

TEST

The test instruction, BIT, tests one bit. For example, suppose that register A contains the number 45d. It would look like this:

binary:     00101101
bit number: 76543210

The 8 bits are numbered 0 to 7; bit 7 is on the far left, with bit 0 on the far right.

Now suppose your machine code program uses the instruction

BIT 4,A

This means “test bit 4 of register A.” Bit 4 is the fifth bit from the right; remember, the first bit is called “bit 0”. As you can see, there is a zero in bit 4. Consequently, the zero flag of the Z80 will go up.

On the other hand, suppose you use the instruction

BIT 3,A

Bit 3 is not 0, but 1. So the zero flag would come down.

You can use the BIT instruction with jump instructions such as JP Z or JR Z to make your program do different things depending on whether a bit is a 0 or a 1. For example,

BIT 4,A
JR Z,branch

would be something like this in Basic:

IF (BIT 4 OF A)=0 THEN GOTO 240

Of course, you cannot say that in Basic since there is no “BIT” function. But you can do it in machine code.

SET

You can also force a particular bit of a particular register to become either 1 or 0. The set instruction, SET, will set the bit to 1; the reset instruction, RES, resets it to 0. For example, suppose register A is 45d. In binary it looks like this:

00101101

Now, if you used the instruction

SET 7,A

register A would have a value of

10101101

or 173d. The difference is that bit 7, on the far left side, has been set to 1.

Then if you used the instruction

RES 3,A

register A would look like this:

10100101

Bit 3 has now become a zero, and register A has a value of 165d.

Get the idea? SET makes sure that the bit is 1; RES makes sure that the bit is 0. That will not always change the value of the number; if you try to set a bit that is already 1, or reset a bit that is already 0, nothing will happen. However, if you do a SET or RES, you will know for sure what the bit will be.

What good is knowing that? Well, sometimes it is critical that a certain bit be 0 or 1. For example, when you use the ROM subroutine CALL 16, the character whose value is in register A will be printed on the screen. However, that must be a number between 0 and 63 or 128 and 191 (the only exception is the ENTER code, 118). These numbers all have one thing in common: bit 6 is always zero. If bit 6 is 1, the system will crash. To keep that from happening, you could use the instruction

RES 6,A

before you

CALL 16

Then you would know for sure that bit 6 is zero and that the CALL will not crash the system.

BIT, SET, and RES can be used with any bit of any of the regular-size registers: A, B, C, D, E, H, or L. As usual, you can also use register pair HL as a pointer to a byte in memory with these instructions.

Shifting Gears

You can also move bits in a register. That should not be a surprise. After all, to the Z80, a number is just a line of bits. You can shift them down through a register in one direction or the other with a shift instruction. Or, if you like, you can run the bits around in a circle with a rotate instruction.

We have already encountered the shift instruction in dividing and multiplying by 2. A shift left instruction (SLA) moves all the bits to the left one position. For example, suppose that register C holds 203. In binary it looks like this:

11001011

After a “shift register C left” instruction (SLA C) it would look like this:

10010110

Notice that all the bits moved one position to the left, and a zero was added on the far right side at bit 0. The original bit 7, on the far left side, seems to have disappeared. But it is not really gone. In case you need that bit, the carry flag keeps track of it. If the bit was 1, the carry flag goes up; if the flag was 0, the carry flag goes down. The process looks something like this:

carry flag <-- register <-- 0

In short, a zero is pushed in on the right side, and the left bit drops into the carry flag. If the number is less than 128, this instruction has the effect of multiplying it by 2.

There are two “shift right” instructions that can be used to divide a number by 2. The first is the “shift right logical” (SRL). It pushes a zero in on the far left at bit 7; bit 0, on the right, drops into the carry flag, like this:

0 --> register --> carry flag

There is also a “shift right arithmetic” instruction (SRA). This one works a bit differently: instead of pushing a zero into bit 7, it just leaves it alone. However, it also shifts everything down, and bit 0 once again drops into the carry flag. This instruction is used because sometimes bit 7 is used as a “sign” bit. When that is the case, it is important that bit 7 stay the same when the number is shifted:

 _
|_> register --> carry flag

The Circle Game

Now comes the interesting part: getting the registers of the Z80 to go around in circles. You can do this with one of the four “rotate” instructions.

“Rotate left” (RL) works like this:

1) The carry flag is pushed into the right side of the register at bit 0.

2) Everything moves over one bit.

3) Bit 7 drops into the carry flag.

It looks something like this:

carry flag <-- register <-- carry flag

“Rotate right” (RR) is just the opposite:

carry flag --> register --> carry flag

As you can see, the bits actually do go in a circle. If, e.g., you did nine RR H instructions in a row, register H would end up exactly as it had started. But it does take 9 not 8, rotates, since the circle includes the carry flag.

You can tighten up the circle by using the “rotate left circular” (RLC) and “rotate right circular” (RRC) instructions. These instructions actually rotate just the eight bits of the register in a circle. RLC moves everything to the left, and bit 7 becomes the new bit 0. RRC moves everything to the right; bit 0 becomes the new bit 7. In each case, the bit that gets bumped to the opposite end is also copied into the carry flag. If the bit is 1, the carry flag goes up; if the bit is 0, the flag comes down.

Perhaps this all sounds interesting, but pretty useless. Why would anyone want to run the bits of a register in a circle?

Actually, these instructions are usually used with register pairs to multiply or divide by 2. For example, you can divide a number in register pair BC by 2 with these instructions:

SRL B
RR C

Here is what happens: the “shift right logical” instruction shifts all the bits in register B to the right, dividing it by 2. Bit 0, of course, gets pushed into the carry flag. But we want that bit to become the new bit 7 of register C. So the “rotate right” instruction gets that bit from the carry flag and pushes it into the left side of register C, moving everything else to the right and dividing it by 2. It looks something like this:

0 --> register B --> carry flag
carry flag --> register C --> carry flag

You can multiply register pair BC by 2 with this set of instructions:

SLA C
RL B

Once again, you can use these instructions with any of the regular 8-bit registers, or by using register pair HL as a pointer to a byte in memory.

Let’s Get Logical

We already know about the ADD and SUB instructions, which let you add or subtract a number with what is in register A. Along with these “arithmetic” instructions, there are also three “logical” instructions: AND, OR, and XOR.

Each of these instructions compares a number with register A, one bit at a time. The two values in bit 0 are compared, and the result goes in bit 0 of register A. Then the bit 1s are compared, the result going into bit 1; then the bit 2s are compared, and so on through bit 7. Exactly what the result of each comparison is depends on which logical instruction is being used.

For example, when AND compares two bits, the result is 1 only if both bits are 1. If either bit is 0, the result is 0.

When OR compares two bits, the result is 0 only if both bits are 0. If either is 1, the result is 1.

XOR, sometimes called the “exclusive-OR,” is a little different. When XOR compares two bits, if the bits are the same, the result is 0; if the bits are different, the result is 1.

A few examples will show how these operations work.

AND is often used to find out whether a particular bit is 1 or 0. For example,

register A: 10010100
AND 00000100
result: 00000100

You can use the AND instruction, then a jump depending on whether bit 2 is one:

AND 4
JR NZ, branch

However, you can do the same thing with a BIT instruction:

BIT 2,A
JR NZ, branch

AND can also be used to make sure a particular bit is zero. For example,

register A: 10010010
AND 11111101
result: 10010000

You can usually do the same thing with an RES instruction.

OR can be used to make sure a particular bit is 1. For example:

register A: 10010010
OR 00000100
result: 10010110

Of course, you can get the same result with a SET instruction.

XOR is really the only one of these three instructions that does something unique: it can “flip” a bit. For example,

register A: 10010010
XOR 10000000
result 1: 00010010
XOR 10000000
result 2: 10010010

Notice how bit 7 has been reset in result 1, then set again in result 2. To do this using SET and RES instructions you would have to do something like Figure 1.

There is one other thing you should know about the logical instructions: no matter what the result is, they always bring down the carry flag. Whenever you need to make sure the carry flag is down, you can use an instruction such as:

OR A

It will not change the value in register A (can you figure out why?); it just guarantees that the carry flag is down.

Figure 1.

        BIT 7,A      ;test the bit
JR Z,skip1 ;if it is 0, jump to "skip1"
RES 7,A ;if it is 1, make it 0
JR skip2 ;jump to "skip2"
skip1: SET 7,A ;if it is 0, make it 1
skip2: ... ;(next instruction)

Flashdance

A few months back, we put together a program that reversed everything on the screen. To demonstrate how the XOR instruction can be used, this time we will make the screen “flash” by switching what is on the screen from regular characters to reversed characters and then back again. The routine also demonstrates how you can put a “pause” in your machine code programs—just as you can in Basic.

The program is in Figure 2. Since it is such a short, simple routine, there are no machine code variables. Register C keeps track of how many times the screen has been reversed. It starts at 2 and then drops by 1 each time through. When it reaches zero, the routine returns to Basic.

The section from the line labeled “start” down to “delay” is the routine that reverses the screen. It checks each byte, beginning at the start of the display file. If the byte is a regular character, it is reversed using the instruction

XOR 128

This “flips” bit 7 of the character. (If bit 7 is a zero, it is a regular character; when bit 7 is 1, the character is reversed.)

If the character is an ENTER (character code 118), it is not XORed; instead, register B is decremented. Register B starts out at 22; after all 22 lines on the screen have been reversed, register B is 0, and the reversing routine is finished.

Take a careful look at the section starting at the line labeled “delay.” This is the “pause” routine. Here is how it works: 60 times each second the computer sends a picture to your TV screen, andf, every time it does, it reduces by one the system variable called FRAMES. However, the top bit of this double-sized variable is always kept as 1, so that FRAMES is always a number between 32768 and 65535.

At “delay” we put FRAMES in register pair HL, and put 15 in register pair DE. Then we subtract DE from HL with the instructions

OR A
SBC HL,DE

The SBC instruction (SuBtract with Carry) will subtract DE from HL—but it will also subtract one more from HL if the carry flag is up. That can be useful sometimes, but not here. We use OR A to make sure the carry flag is down, so we know we will get the correct answer to HL minus DE.

Next we SET bit 7 of register H. Now HL holds the same number that FRAMES will hold once it has sent 15 more pictures to the TV screen, i.e., in about 1/4 second. We move that number to register pair DE.

Finally, in the section labeled “loop” the program compares the number in DE to FRAMES again and again. It keeps jumping back to “loop” until at last they are the same; then it goes on to decrement register C and either reverse the screen again or return to Basic. You can use the “pause” routine with any machine code program. Depending on what value you load into DE, your program can pause as little as 1/60 of a second or as long as 9 minutes. Since machine code works so fast, sometimes that is a very good thing to have.

Use the Basic programs in Figure 3 to load the “flasher” routine into high memory, then try it out with a short program such as in Figure 4. It will work in as little as 1K RAM, but it does need the 8K ROM. Otherwise, you will not be able to see the screen flash.

Figure 2.

0E 02              LD C,2           ;reverse screen twice
06 16 START: LD B,22 ;22 lines
2A 0C 40 LD HL,(D-FILE) ;start of display file
23 TOP: INC HL ;next character
7E LD A,(HL) ;get it
FE 76 CP 118 ;is it an ENTER?
28 05 JR Z,line ;if so, skip ahead
EE 80 XOR 128 ;reverse character
77 LD (HL),A ;replace the character
18 F5 JR top ;do it again
05 LINE: DEC B ;next line
20 F2 JR NZ,top ;if less than 22 lines
2A 34 40 DELAY: LD HL,(FRAMES) ;current FRAMES
11 0F 00 LD DE,15 ;pause time
B7 XOR A ;reset carry flag
ED 52 SBC HL,DE ;HL=HL-DE
CB FC SET 7,H ;to match FRAMES
54 LD D,H ;DE=HL
5D LD E,L
2A 34 40 LOOP: LD HL,(FRAMES) ;check till they match
B7 XOR A
ED 52 SBC HL,DE
20 F8 JR NZ,loop
0D DEC C ;finished reversing?
20 D5 JR NZ,start ;if not, jump
C9 RET ;otherwise, return

Figure 3.

First, RUN this program to reserve high memory. The “flasher” program takes 46 bytes.

10 PRINT "HOW MANY BYTES?"
20 INPUT A
30 LET RT=PEEK 16388+256*PEEK
16389
40 LET RT=RT-A
50 LET H=INT (RT/256)
60 LET L=RT-256*H
70 POKE 16388,L
80 POKE 16389,H
90 NEW

Then enter and RUN this program to load the “flasher” routine into high RAM:

  1 REM 0E0206162A0C40237EFE762
805EE807718F50520F22A3440110F00B
7ED52CBFC545D2A3440B7ED5220F80D2
0D5C9
10 LET RSTART=16514
20 LET START=PEEK 16388+256*PE
EK 16389
30 LET A=0
40 LET H=PEEK (RSTART+2*A)-28
50 IF H<0 OR H>15 THEN STOP
60 LET L=PEEK (RSTART+2*A+1)-2
8
70 IF L<0 OR L>15 THEN STOP
80 LET N=16*H+L
90 POKE START+A,N
100 LET A=A+1
110 GOTO 40

Figure 4.

10 LIST
20 LET START=PEEK 16388+256*PE
EK 16389
30 LET A=USR START

The Guided Tour

By now, if you have been following this series of articles, you know something about most of the instructions of the Z80 microprocessor. We have covered such things as registers and flags, loading and jumping, calls and compares. And until now, I have explained what each machine code instruction does and how it works as we encountered it.

Now that you have a good grasp of what machine code is, it is time to take the next step: to explore the instructions of the Z80 in detail. We will do that with a little book that is packed with all sorts of technical information: The Z80 CPU Programmer’s Reference Guide. You can get a free copy of the book from Zilog, the company that designed the Z80, by writing to Zilog, 1315 Dell Avenue, Campbell, CA 95008. Be sure to mark your letter “Attn: Tech Publications” and ask for the guide by its full name.

The guide is filled with charts, diagrams, and explanations, and—as we will see—a few surprises as well.

More Registers?

The surprises start on page 2 of the guide, with a diagram of the registers of the Z80. Some of the registers look familiar. In the “main register set” we can spot A, B, C, D, E, H, and L, along with the flags register, register F. But you will notice that, right next to that diagram, there is another set of registers that looks just like the first one—the “alternate register set.”

These registers are just exactly like the first set. This is a “spare” set. Like a spare tire, it can come in handy for a programmer, though usually you can get by without it. When your program uses the “exchange registers” instruction,

EXX

it is as if you have jacked up your Z80 processor, taken off registers B, C, D, E, H, and L, and put on the spare registers. To get the original registers back, you just use another EXX instruction.

But it is not a good idea to use these spare registers in your machine code programs. The Basic interpreter program in your computer uses some of these registers to keep track of what is going on in Basic. Using the spare registers may crash the computer or make your Basic programs act very strangely.

You can also exchange register A and the flags register with their spares. That happens if you use the “exchange registers A and F” instruction,

EX AF,AF'

—but do not do it!

Why not? Because the Timex and Sinclair computers use the alternate register A for putting things on your TV screen. Sixty times every second when you are in “slow” mode, your ZX81 or TS1000 stops what it is doing and goes to work sending information to the TV. The TV will not wait, so the computer does not have time to check on register A, or do any other kinds of “housekeeping.”

Do not use the alternate registers, or the special-purpose registers I, R, IX, or IY, for any machine code routines on the Sinclair and Timex computers. If you do, you will probably crash the system. That is right—you should not use any of the new registers on page 2. That is why we have not looked at them before. For programming on the ZX80, ZX81, and TS1000, they might as well not exist.

Hot Off the Grid

On pages 4 and 5 you will see some familiar information in a new form. Page 4 contains a grid for instructions in the “8-bit Load Group.” That means they are load instructions that move numbers between regular-sized registers or single bytes of memory. (Remember, the Z80 is called an 8-bit processor because its regular registers handle 8 bits at a time.)

You can use the grid to translate an instruction into the numerical code that the Z80 processor understands. Along the top side of the “8-Bit Load Group” grid are the names of “sources”—the registers and places in memory that a number can come from. Down the left side are the possible “destinations”—places a number can go. To use the grid, you simply choose a load instruction—a source and a destination. Then find the place where the column of the source and the row of the destination meet. That is where you will find the hexadecimal number that matches your instruction.

For example, let’s try the instruction

LD A,B

This loads the value in register B into register A. Register B is the source; register A is the destination. Follow the “B” column down and the “A” column across, and you will see that they meet at the number 78 (78 is in hex, or base 16.)

Now turn to the “Character Set” appendix in the back of your ZX81 or TS1000 manual. Look down the column headed “Hex” until you find the number 78. You will find that 78h corresponds to 120d—and, just as expected, it also corresponds to the machine code instruction LD A,B.

The appendix and the grid both contain the same information. The appendix is organized with the instructions in numerical order; the guide, according to what each instruction does. Each is handy to have, though most people find it easier to use the grid for translating instructions into the numerical codes.

Try using the grid to find the numerical codes (in hexadecimal) for these instructions.

LD C,(HL)       4E
LD E,4          1E 04
LD (18418),A    32 F2 47

You will notice that the grid only gives you the first part of the instruction. As usual, you still have to translate the rest of the instruction into the appropriate numbers, whether decimal or hexadecimal, for the second or third byte of the instruction.

Everything You Ever Wanted to Know About…

Page 5 has, in compact form, a tremendous amount of information about each 8-bit load instruction.

For example, the first line tells us all about loading information from one register into another. (The small “r” means any one of the regular registers. Look down at the bottom of the page under “Notes” and you will find a note that tells you just that.)

What does it say about the instruction? First, it shows us exactly what happens when the Z80 processor performs the instruction. The arrow shows you where the number moves—to the first register (the destination) from the second register (the source). This simple system for indicating what happens can be very useful, especially if you are exploring an instruction that you have never used before.

Next, it shows what happens to the flags when the Z80 performs the instruction. Some instructions will always raise, or set, a particular flag; others will always lower, or reset, the flag. Some instructions will affect a flag depending on the result of the instruction.

In this case, none of the 8-bit load instructions affects any of the flags. That is what the black dot under each column means—that the flag is not affected. The note on “Flag Notation” at the bottom of the page shows the effect on the flag:

. = Not affected
1 = Always raised (or set)
0 = Always lowered (or reset)
0 = Effect depends on the
    result of the instruction.

Some of the flags are really useful only for specialized, complicated tasks, but three of them can be very handy. We already know about the zero flag and the carry flag. Information about them is in the columns headed with the letters Z and C. The zero flag is usually raised (or set—the words mean the same thing) when an addition or other operation results in a 0. The carry flag is raised when the result is greater than 255, or less than 0. However, some instructions will affect these flags in ways you might not expect. Do not try to guess—always check the chart to be sure of how flags are affected.

One other useful flag is the sign flag. If the result is greater than 127, i.e., if bit 7 is one instead of zero, the S flag will often be set. (Remember, bit 7 is sometimes used as a “sign” bit; that is where the name of the flag comes from.)

Like most Z80 manuals, the guide uses the words “set” and “reset” rather than “raised” and “lowered” for flags. These are jargon words, but they are the jargon the guide uses. So to avoid confusion, we will use them too. Just remember: “set” means the flag is up; “reset” means the flag is down.

One other column in this chart can be very useful: the column headed “No. of bytes.” This column reminds you of exactly how many bytes long each type of instruction should be. When you translate an instruction into numerical code, that can be a big help. It may keep you from forgetting how many extra bytes some instructions require.

Once over Lightly

Pages 6 and 7 give the same information for load instructions for the register pairs and double-sized registers—the “16-Bit Load Group.”

Pages 8 and 9 cover the exchange, transfer, and search groups. Though there is no space to explain these instructions in detail right now, you might want to take the time to look at the “symbolic operation” column. You may be able to figure out what each of these instructions does just from the grids and charts, now that you know how to read them.

Page 10 covers 8-bit addition and subtraction and the logical instructions. Page 11 includes some general arithmetic instructions such as NEG, along with a few special control instructions. In general, you should not use the “Miscellaneous CPU Control” instructions on your Sinclair or Timex computer; most of them stand a good chance of crashing the system.

Then the guide continues through the rest of the instructions: 16-bit arithmetic; jump; rotate and shift; test, set, and reset; call; and so on. The “input” and “output” instructions are really only useful if you are a hardware designer; the same is true of the information about the “interrupt structure” of the Z80.

At the very back of the guide is a very technical section—all about three special chips that are often used with the Z80 processor. If you have some background in digital circuit design, you may find this section interesting and useful. If not, do not worry. You do not need to know anything about the PIO, CTC, or SIO to program your ZX80, ZX81, or TS1000.

Coming Attractions

Next time, we will return to some really practical machine code programming: we will look at a way to draw circles on your screen. Maybe you think it takes the SIN and COS functions in Basic to draw a circle, but, as we will see, you can do it better and faster with a simple algorithm that draws a circle four times as fast as SIN and COS—and that is still in Basic. In machine code, it is really fast.

If you have comments or questions about machine code programming, or something is not quite clear, let me hear from you. Be sure to send along a stamped, self-addressed envelope if you need a reply.

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.