by DR. IAN LOGAN

a ea a a ae ce ea i cael ee ae eee ee ee ae cae ek ae one dd een ns erp oe ee eh Ye em a ae iw TTBS SE SS TTS SS STS SSS SH TMM DSS SSS SS TOSI SSS SSMS STI TST STS SST SSS SST

ee ee ee em e Se PTT BTS DS STH SSR TS STP TT TTBS TSS SSS SE SS SVS LS SS VT SS SS SVS SS SS SS SSS SS SS ae ee =— = =

SINCLAIR DEVELOPS A 'NEW' 8K ROM:

The originad 8K ROM issued by Sinclair Research in March 198] has unfortunately been found to contain several errors. The major problem is errors in calculations:

e.g. PRINT 0.25 ** 2 gives 3.1423844, which is rather a long way from the correct answer.

As well, the line POKE 16437, 255 has to be added for safety after every use of the PAUSE command to prevent the ‘white-out' effect.

These failures in the program of the 8K ROM have resulted in the issue of a ‘new’ 8K ROM by Sinclair Research.

This new ROM can be identified by obtaining the following results: - PRINT 0.25 ** 2 gives the correct answer 0.0625 - PRINT PEEK 54 gives 136

(Both tests are necessary as there are just a few ZX 81s that contain a hardware add-on to make them count properly, but they do not contain the 'new' ROM.)

The differences between the 'new' and the ‘old' ROMs are:

1) The workspace is cleared in the INPUT command routine (a house-keeping error)

77) FRAMES-high, 16437, is loaded with 255 on every return from PAUSE. (a very good idea.)

i171) A change has been made in the VARIABLE routine at 1O2F Hex. (the reason for this is not known as yet)

iv) And most importantly the three troublesome '‘extra'bytes at 1733 - 1735 Hex. that lead to the arithmetic error are simply deleted.

Although it is as yet unconfirmed by Sinclair, it would appear that the hardware add-on that corrects the arithmetic on some of

the ‘old' 8K ROMs works by nullifying the effect of the ‘three bytes'. Probably when the location 1735 is addressed the instruction fetched is ‘LD H,A' but the instruction passed to the Z80 is 'DAA'.

Readers of this book that are using machines fitted with the ‘new’ ROM will have to bear the following points in mind:

The addresses of the routines between 0000 and OEE9 are unchanged. Between OF20 and 1022 they are moved up by 3 bytes.

Between 1046 and 1716 they are moved up by 4 bytes.

Between 1737 and 1DE1] they are moved up by 1 byte.

The character generator remains at JEQ0O.

The changes mean that in:

Chapter 4: the references to change are the CLEAR command routine is at 149A the ‘assignment of a string variable’ routine is at 13C8 the FAST command routine is at OF23 the SLOW command routine is at OF2B.

Chapter 6: the references to change are Floating point handling routine - 158A The function table - 1915 The floating point calculator - 199D DIM - 1409 CLEAR - 149A PAUSE - OF32 SLOW - OF2B FAST - OF23

Chapter 7: the change to make is As SLOW is now at OF2B the value to be entered in location 16534 1s changed to 43 decimal. Remember the checksum will go up by 3.

CONTENTS

Chapter

. Introduction

The Z80 Microprocessor

The Simple Mathematics

The Z80 Machine Code Instruction Set Demonstration Machine Code Program

An Examination of the 8K Monitor Program

Using Machine Code Routines in BASIC Programs

NOOR ON =

Appendices: i. Extracts from the 8K Monitor Program The SAVE command routine The LOAD command routine The Keyboard Scanning rouinte The Keyboard Decode routine li. Tables of Z80 Machine Code Language Instructions ili. A Decimal-Hexadecimal Conversion Table iv. Table of ‘Key Values’

155

Preface

in the spring of 1980 Science of Cambridge (now Sinclair Research) launched the ZX-80. It was the first of a new type of microcomputer for the hobbyist. At last there was a very cheap and reliable machine that together with an ordinary T.V. set and a cassette player formed a power- ful home microcomputer system.

Although the ZX-80 was highly successful it was possible for Sinclair Research to put a much improved version on the market by the spring of 1981. This second machine is called the ZX-81.

The ZX-81 is supplied with a 8K ROM that contains the operating system program and a floating-point BASIC interpreter. The BASIC is very easy to use and is quite fast enough for most simple programming tasks. The added feature of ‘syntax checking’ is really quite a remarkable extra to be found on such a small machine.

However once BASIC has been mastered the attraction of machine code programming offers to the programmer, the possibility of producing programs that RUN at great speed, and can be as complicated, for their size, aS any programs written for larger machines.

The main themes of this book are to develop an understanding of the Z80 machine code language and to discuss the actual workings of the 8K monitor program.

It is hoped that readers with only a knowledge of BASIC, will gain the ability to write short machine code programs for themselves and thereby derive even greater pleasure from their ZX-81.

4

1. Introduction

1.1 This book can be divided into two major parts.

The first part, chapters 1-4, discuss the Z80 microprocessor and its machine code instructions.

_ The second part, chapters 5-7, deals with actual machine code prog- rams. Chapter 5 containing programs that illustrate the different types of machine code instructions in the Z80 instruction set. Chapter 6 dis- cusses the 8K monitor program and chapter 7 gives some suggestions on how to go about writing a machine code program. |

Throughout the book there are many references to the 8K monitor program. This program being chosen as an example program because it is the only machine code program that is supplied with the standard ZX-81.

It is assumed that the readers of this book will already have a fairly good understanding of the BASIC language as used in the ZX-81. New terms will be explained as they occur, drawing only on that knowledge of the BASIC language.

1.2 The standard ZX-81 microcomputer system:

The standard system comprises:

1. The ZX-81 mainboard with 1-16K RAM (or more)

2. The keyboard, (integral with the mainboard unless otherwise adapted).

3. The T.V. receiver.

4. The cassette player. This standard system can be shown diagrammatically as:

T.V. RECEIVER MAINBOARD

Display output SINCLAIR

Keyboard input

CASSETTE PLAYER

KEYBOARD

Diagram 1. The standard ZX-81 microcomputer system

rs)

Before the power supply is connected to the mainboard, it is really quite obvious that no work can be performed by the system. However once the power is connected the Z80 microprocessor starts working executing instructions sequentially at its operating speed of 3.25 mhz. A simple instruction will take 1.23 microseconds and the longest instruc- tions no longer than 7.46 microseconds. The microprocessor then con- tinues to execute between 141,00 and 812,500 machine code instruc- tions each and every second until the power is turned off.

This book aims to develop an understanding for the reader of just what the computer system is doing all the time, and why even very simple tasks sometimes take a lot longer than ‘one eight hundred thousandth’ of a second to be completed.

This book also introduces the reader to the subject of monitor prog- rams but let it suffice for the moment to say that it is the monitor program that is followed by the Z80, unless the BASIC USR command is ean used, and it directs the ZX-81 to;

“Produce” a screen display.

“Scan” the keyboard to detect keystrokes.

“Provide” a system for the LOADing and SAVEing of programs on cassette tape.

“Give” the user the BASIC language.

2. The Z80 Microprocessor

2.1 The Z80 in outline.

The ZX-81 microcomputer has as its largest and most important ‘silicon’ chip a Z80 microprocessor. The Z80 is so called because it was de- veloped by Zilog, inc. of California, U.S.A. This company expanded and improved an earlier microprocessor, the INTEL 8080. The figure ‘8’ in the name also implies that it is an eight bit microprocessor.

A microprocessor is a ‘silicon’ chip, and incommon with other ‘chips’, it has input lines (= wires) that carry electrical impulses into the chip, output lines that carry impulses away, and power and ground connections.

But a microprocesor is a very specialised chip, that as the name implies has been designed to perform specifically as a small ‘processor or computer.

Internally it is amazingly complicated, but fortunately the internal structure can be divided into five functional parts. These are the Control Unit, the Instruction Register, the Program Counter, the 24 User- registers and the Arithmetic-logic unit.

This simplified view of the internal structure of the Z80 is shown diagrammatically in diagram 2.

|

5 Address Control! lines Unit 11 address lines Program Clock Instruction Register 8 : Data lines 24 User 8 Registers Control lines 2 es) Arithmetic- aN ie Logic-Unit lines

Diagram 2. The Z80 microprocessor in outline.

7

A Z80 microprocessor only works as a computer because it is a machine capable of following a ‘stored program’. This program is re- quired to be in the form of a sequence of machine code language instructions, that the Z80 can execute, together with any data that is required. The whole of this program must be present in memory that can be accessed by the Z80.

The 8K monitor program is such a program, and by being supplied ina ROM (read only memory) it is permanently present in memory. indeed the standard ZX-81 has the monitor program so placed in memory that when the power to the Z80 is turned on, it is this program that is followed immediately.

2.2 The Data and Address buses

The Z80 microprocessor cannot work in isolation and it must therefore have connections to the other parts of the system. These connections are of three types, viz. the Control lines, the Data lines and the Address lines.

The Control lines are single tracked (= 1 wire), whereas the Data lines are usually collected together as an 8 track DATA BUS and the Address lines as a 16 track ADDRESS BUS.

The Control lines will be discussed in the next section.

The Data bus is used to carry 8 binary digits at a time, in parallel. The level of the voltage on a particular line signifying whether the line is carrying a binary 0 or a binary 1. Each binary digit is usually called a ‘bit’ and a collection of 8 bits held together for a particular purpose is called a ‘pyte’. The Data bus is therefore said to be able to carry ‘1 byte’ of data at a time. The term ‘byte’ is commonly used to describe a ‘place’ where 8 bits of data would fit, rather than to an actual ‘byte’ of data.

The Address bus has 16 tracks and is therefore described as being ‘2 bytes’ in width.

It is a fundamental principle of the Z80 that data is held as a byte of 8 binary digits and an address is held always as 2 bytes, that is 16 binary digits.

The Data bus is used to carry bytes of data to and from the Z80 and it therefore physically links the Z80 to the RAM chips (random access memory) and the ROM. The Data bus is also joined to the circuitry of the keyboard, the T.V. display and the cassette player interfaces.

The Address bus also links the Z80 to the RAM chips and the ROM, and in the ZX81 there are certain links to the keys of the keyboard.

Diagram 3 shows the Z80 and the main bus system.

8

The 16 bit wide ADDRESS BUS

&

data trom ree data to and keyboard The 8 bit wide DATA BUS from T.V. and

cassette player

Diagram 3. The Address bus, the Data bus and the Z80.

The Address bus is used to hold the addresses of the location in the memory of the Z80, whether it be RAM, ROM or something else. As the Address bus can hold a 16 bit binary number it follows that the range of addresses that can be present on the Address bus can range from;

binary 0000 0000 0000 0000 11114 1111 1111 1111 which has the decimal equivalent of;

0 65535 (location 0 being the first location)

When the Z80 is running, bytes of data are continually being READ from memory and WRITTEN into the memory.

In order to perform a READ operation, the specific address of the required location in memory must first be placed on the Address bus, then the byte of data in that location can be copied and the copy passed along the Data bus to the Z80.

In order to WRITE a byte of data into the memory, the required address must first be placed on the Address bus, then the Z80 puts the byte of data onto the Data bus and the memory chip subsequently collects the byte of data.

The five functional parts of the internal structure of the Z80 will now be discussed in turn.

2.3 The Control Unit.

The Control unit of the Z80 can be likened, in a simplistic manner, to the ‘manager of a production line’. It is therefore the responsibility of the Control unit, the manager, to arrange that materials (data) are brought into the Z80, that finished products (also data) are sent out to the correct destination and to ensure that the ‘production’ is timed successfully.

In the case of the Z80 there are a large number of different timing signals that are generated. Some of these signals are used only within the Z80 itself, with the rest being put out on the Control Lines.

The Control Lines are those lines that carry ‘signals’ to and from the Z80. For example there is a control line called ‘READ’ that is used during the operation of reading data from outside the 280.

It is important to understand that the Control Unit, like the production manager, is in no way responsible for deciding which work is to be done, only for actually doing the work. The Z80 has to follow the ‘program’ as written by the programmer and the production manager has to follow the ‘program’ as set out by his company directors.

A more detailed discussion on the Control Unit and the Control signals is beyond the scope of this book.

2.4 The Instruction Register

The term ‘Register’ is used to describe a single byte location within the Z80 itself. It therefore is an actual place where 8 bits of data can be held. In the Z80 there are a whole series of registers and the moving of bytes of data ‘into and out of’ registers is the most important single feature of machine code programming.

The Instruction Register is a register within the Z80 that has the specific purpose of holding a copy of the instruction that is currently being executed.

As was Said earlier, the Z80 microprocessor only works as a computer because it is a machine capable of following a stored program. |

When the Z80 is following such a program, a copy of each instruction in turn will be placed in the Instruction Register prior to its being decoded and executed by the Z80.

2.5 The Program Counter

The Program Counter is not a single register but is a pair of registers within the Z80. it is used for the specific purposes of holding the address of the location in memory either of the current instruction that is being ‘executed’, or of the next instruction to be ‘fetched’.

When an instruction is to be ‘fetched’, the Control Unit arranges that a copy of the contents of the location that is addressed by the Program Counter, is loaded into the Instruction Register. It is also one of the jobs of the Control Unit to ensure that the value in the Program Counter is then changed so as to ‘point’ to the location of the next instruction.

10

The actions of the Program Counter are very similar to those of the BASIC interpreter’s ‘Line number of current statement variable. (16391 - 2). This variable holds the line numbers of the ‘current statements’ as the interpreter goes through the lines of a BASIC program.

2.6 The User-Registers. (Main registers)

There are 24 User-Registers within the Z80. They have been termed ‘User’ registers because they can be filled with specified bytes of data by the programmer.

The names given to these 24 different registers are not at a first glance logically arranged. The reason for this state of affairs being that the Z80 is a microprocessor that has evolved from earlier, and less complicated, models. Certain of the names hark back to the earliest microprocessors that were ever made, whilst later names have been added in an ‘ad hoc’ fashion. Some names proving to be more appropriate, and informative, than others.

All of the registers, strictly, are single byte registers but they are commonly used as register pairs.

The following diagram shows the 24 User-registers of the Z80 dis- played as 12 register pairs, The ‘bit numbers’ are also shown.

Main Set Alternate Set

,

, ,

76543210 76543210 76543210 76543210

: ; -

76543210 76543210 76543210 76543210

76543210 76543210 76543210 76543210

76543210 76543210 76543210 76543210

76543210 76543210 Diagram 4. The 24 User-Registers of the Z80.

11

Each of these registers will now be discussed briefly: The A register:

This register is the single most important register of the Z80. It is often called the ACCUMULATOR, a name that goes back to those models in which there was only one register that could be used to ‘accumulate’ a result.

In the Z80 the A register is extensively used for arithmetic and logical operations, and indeed there are many operations that can only be performed using the A register.

There is a great number of different ways in which a byte of data can be entered into the A register by the programmer and hence there are many machine code language instructions that involve the use of the A register.

The F register:

This is the FLAG REGISTER and it is often considered to be a collection of 8 bits rather than a true register.

The concept of flags will be dealt with fully in chapter 4, but simply a flag is a ‘bit’ that is given the value 0 (RESET) or the value 1 (SET) depending on the result of the operation.

The flag register does have 8 bits but the programmer is really only concerned with the ‘4 major flags’. These are called the Zero flag, the Sign flag, the Carry flag and the Parity/overflow flag.

The ‘minor flags’ are used by the Control Unit and cannot directly be used by the programmer.

The HL register pair:

in early microprocessors the register that was used to hold addresses was a single byte ‘address register’, and was capable of addressing 256 locations. However when 2-byte address registers were introduced, one of the registers was called the ‘high address register’ and the other the ‘low address register’. A register pair is capable of addressing 65536 locations.

The ‘H’ and ‘L’ therefore derive their origins from the words ‘high’ and ‘low’. It is also interesting to note that the ‘high’ register, being a later development has lead to the situation whereby an address, is always given as the ‘low’ byte followed by the ‘high’ byte.

In the Z80 the HL register pair is just one of three register pairs that are used to hold addresses. However the HL register is the most important. The HL register pair can also be used to hold 16 bit numbers, rather than addresses, and there are a certain number of arithmetic operations that can be performed on these numbers. The registers of this pair can also be used as single byte registers. However there are relatively few opera- tions that can be performed on the H register, or the L register, as compared to the A register.

12

The BC and DE register pairs: 7

These are the other register pairs that are predominantly used within the Z80 to hold addresses. It would appear that their names were simply derived because an ‘A’ register already existed.

Once again the programmer may use the registers as single registers, and also there are certain instructions that use some of these registers as counters.

The Alternate register set:

The 280 is an interesting microprocessor in that it has an alternate register set for the A, F, H, L, B, C, D & E registers. These alterate registers are designated for A’, F’, H’, L’, B’, C’, D’ & E’ registers.

There are two special instructions in the Z80 instruction set that allow for the contents of the alternate set of registers to be exchanged with the contents of the current main set of registers. Once the registers have been exchanged the Z80 will work with the ‘former alternate set’ believ- ing it to now be its ‘main set’. The ‘former main set’ will now be treated as an ‘alternate set’.

The programmer may exchange the register sets, totally or in part, as often as he wishes in a particular program.

The concept of there being alternate registers may sound to be very simple, but in practice it is far from being so. The problem is that the programmer has to make sure that he knows which set of registers is actually being used at a particular moment, as there are no machine code instructions that only work on one set of registers and not the other.

Consequently there are many programmers that never use any of registers in the alternate set, and their programs are perfectly successful. However programs that take full advantage of the alternate set of re- gisters may run faster than programs that do not. |

In many Z80 systems the use of the alternate set of registers is restricted, and indeed this is the case in the ZX-81 system running with the 8K monitor program. This means that a machine code program that is to ‘return’ to BASIC must not use some of the alternate registers, how- ever a Self-contained machine code program is quite free to use the full set of alternate registers.

The IX and IY register pairs:

These two register pairs are used to perform operations using ‘index- ing’. This is a facility which allows for entries in a list or table to be manipulated as long as the Index Register pair being used holds the ‘base’ address of the table or list, and the position of the required entry is known relative to the ‘base’ address.

The Stack Pointer: The Stack Pointer is a register pair that is used to ‘point’ to a location in memory in an area called the ‘stack’.

13

All microprocessors in current use require a stack, that is an area of memory to use as a working space for the storage of addresses or data on a temporary basis. Such a working area is called a stack because each entry is stacked next to the previous one.

The Z80 uses a stack that ‘grows downwards’ in memory, so an analogy might be to a high rise block of appartments in which the first tenant moves into the top appartment, the next tenant into the one below and so on downwards. The stack is used on a first-in last-out principle, so the first tenant to move out will always be the latest tenant to have moved in.

The stack pointer is used to point to the different locations in the stack in a very special way. The stack pointer always holds the address of the last location to have been filled. Therefore when a new entry is to be made, the Control Unit first arranges for the value of the stack pointer to be decreased by one (decremented) so as to point to the actual location that is to be filled. The required data is then moved to this location.

When data is being removed from a stack the stack pointer has to be increased in value.

To be a little more precise the stack pointer is always decremented twice when data is added to the stack, and incremented twice after data has been removed from the stack. This is because all data movements involving the stack require the handling of two separate bytes of data.

It is an important point that strictly data is not removed from the stack but only a copy of the data is made, and the data still remains in the locations until it is overwritten at a later date.

To the programmer the use of the stack is almost a challenge. Once again there are many programmers that shy away from using the stack to temporarily hold data, preferring to use ordinary memory locations in- stead. Programs that do not use the facility of the stack may not run quite as fast as those programs that do use the stack because moving data to and from the stack is very quick.

The | register:

This is the Interrupt Vector register. The Z80 in its normal running state executes sequentially the instructions in a machine code program. How- ever this ‘normal’ execution of a program can be ‘interrupted’. In most Z80 systems the ‘interrupts’ would be generated at the request of such devices as printers, disk units and clocks. However in the ZX-81 system ‘interrupts’ are only used when forming the T.V. picture.

When a device wishes to interrupt the Z80 it places a signal on the appropriate control line. The Z80 then responds by stopping its execution of the normal program and attends to the request of the device.

Inthe ZX-81 system an ‘interrupt’ will lead to the execution of either the routine that is located at address 0038, or the routine that is located at address 0066.

14

However in larger systems many interrupt handling routines may be needed and the Interrupt Vector Register is used to hold the ‘high byte’ of the address of a ‘table of addresses’ for the different handling routines. When the | register is used in this way up to 128 different addresses can be held in a single table.

The R Register:

This is the Memory Refresh Register. This register is just a simple counter that is incremented every time an instruction or a byte of data is fetched from the memory. The value held in the register therefore alters between 0 and 255, over and over again.

In most Z80 systems this register is used to indicate which locations in memory need to be refreshed (recharged) at a particular time. However in the ZX-81 system the R register is used to count the number of characters that go to form a single line of the T.V. display.

2.5 The Arithmetic-Logic Unit:

The Arithmetic-logic Unit, the ALU, is the last of the functional blocks of the 280, and it is concerned, as its name implies, which arithmetic and logical operations.

lt is important to realise that the actual operations that can be performed by the ALU are very limited in scope.

Simply binary addition and subtraction are possible, but not binary multiplication or division, as these latter operations are very complex in binary arithmetic. Incrementation (adding 1) and decrementation (sub- tracting 1) are just special cases of addition and subtraction and are readily managed. The unit is also able to perform a large number of ‘bit’ operations, by this is meant that it can assess the value of a single bit from within the byte held in the unit at a particular moment.

All of the above operations are discussed fully in chapter 4.

2.6 The Concept of machine code instructions:

Now that the ‘hardware’ has been discussed it is appropriate to dis- cuss the actual structure of a machine code program. Machine code program instructions are usually written in an ‘assembler language’ format, this means that ‘mnemonics’ (words) are given to each instruc- tion so as to make it easier to read. Otherwise a machine code program would appear as a simple list of numbers in binary, hexadecimal or decimal arithmetic.

There is fortunately a great similarity between the structure of a BASIC program and that of a machine code program.

A BASIC program is made up of a set of BASIC lines, each with a line number that shows its correct position in the program, and in turn each BASIC line is made up of an initial command followed, if necessary, by further data.

15

A machine code program can have its structure described in exactly the same way. A program is made up of a set of instruction lines, each of which has allocated to it, an address in memory where the line is to be placed, and in turn the instruction line is made up of an initial instruction code followed, if necessary, by further data.

In the ZX-81 BASIC there are only 31 commands but in the Z80 machine code langauge there are over 500 different instructions. Fortu- nately though, the situation is helped by the instructions being easily divided into 18 smaller groups.

The Z80 instruction codes are 1-2 bytes in length, and of the 256 different numbers that can be held in a single byte, 252 numbers cor- respond to 1-BYTE INSTRUCTIONS. The remaining 4 numbers are used to form 2-BYTE INSTRUCTIONS.

Throughout this book the term ‘instruction code’ is reserved for de- scribing the 1, or 2, bytes of the actual instruction, and where data has to be placed after the instruction code, this data will always be described as ‘data’. |

The full instruction length of the instructions in the Z80 machine code langauge is said to be between 1 and 4 bytes, as there are no instructions that taken together with any required data occupy more than 4 bytes.

Each of the different instructions has its own mnemonic, and these have been chosen to explain what the instruction is actually doing. E.G. a simple instruction mnemonic is ‘LD A, B’ which can be expanded to give

load a copy of the contents of the B register into the A register’.

To illustrate the points made in this section the following diagram shows a few lines of machine code, together with the ‘assembler’ mne- monics and an attempt using BASIC to show just what the lines achieve.

Indeed practically all machine code programs can be described in a PSEUDO-BASIC, and to the programmer new to machine code language programming, the approach can be very helpful.

___Machine Code Language BASIC Language address line No. Line

052B 3E 78 1323 LET A=120

052D 5F 1325 LETE=A

052E 218204 | LD HL+048211326 LET HL=1154 0531 19 ADD HL,DE 11329 LET HL=HL+DE 0532 19 ADD HL,DE 1332 LET HL=HL+DE 0533 ....... continues 1933 53% continues

Diagram 5. An Introductory Machine Code Program

3. The Simple Mathematics

Absolute binary arithmetic

As it has already been said, the Z80 holds numbers which it is manipulat- ing, either as 1 byte of 8 binary digits, or less commonly, as 2 bytes of 16 binary digits.

By saying that a number is held as an absolute binary number it is meant that each byte has the binary range of 0000 0000 - 1111 1111, or the decimal range of 0-255, and importantly there is no way that such a number could ever be considered to be negative.

It is important to realise that all numbers heid in the Z80 are always absolute binary numbers. To a certain extent this can be shown by using the BASIC PEEK command, as this command will return the contents of any of the memory locations as a decimal number in the range 0-255.

The following program shows this in a very simple way:

10 SCROLL

20 PRINT PEEK (RND*65535) 36 GOTO 14

RUN

The program prints the PEEK values and it can be seen that they all lie in the range 0-255 decimal.

It is also important to realise that when operations, such as addition, take the contents of the byte past 255 then the contents will revert to 0, instead of going past 255. An operation such as subtraction will cause the contents of a byte to return to 255 every time 0 is reached.

This behaviour of an absolute binary number can be shown by the following BASIC programs:

For the addition of ‘255+5'

16 LET A=255 20 LET A=A+255 36 IF A>=256 THEN LET A=A—256 46 PRINTA For the subtraction of ‘5-8’ 16 LET A=5 20 LET A=A-8 30 IF A<@ THEN LET A=A+256 46 PRINTA

Ina Z80 system all of the numbers are in ‘absolute binary’, but often the programmer wishes to place a different interpretation on the value of the number. The commonest method in use at the present time is called ‘2’s complement arithmetic’, and indeed in the Z80 instruction set there are several instructions that have been included to help the programmer handle this form of arithmetic.

17

3.2 2’s Complement Arithmetic

The concept behind ‘2’s complement arithmetic’ is very simple, but when it is actually used in a program the results can be very confusing. All machine code programmers must therefore try to become familiar with this important form of arithmetic.

Simply the method enables the programmer to designate the numbers in the binary range 0000 0000 ~ 0111 1111 to the decimal range of 0 to +127, and the numbers in the binary range 1000 0000-1111 1111 tothe decimal range 128 to —1.

A result of this interpretation is to make ‘bit 7’ (the left-hand most bit) act as a ‘sign’ bit. This bit will have the value 0 (Reset) for positive numbers and the value 1 (Set) for the negative numbers.

The following diagram illustrates the method.

BINARY DECIMAL 01111111 01111110

Positive numbers

0000 0010

0000 0001 0000 0000 111111711

Negative ee u nm

Numbers 1000 0001

1000 0000

Sign bit Diagram 6. 2’s complement arithmetic (1 byte)

Fortunately there is an easy way to find the 2’s complement value of the decimal numbers 128 to —1, and that is as follows:

a) form the binary number of the absolute decimal number. e.g. to find the 2's complement of 45, first find the binary equivalent to +45, which is 0010 1101.

b) form the 1’s complement of this number, (simply change all the bits to their opposite values) e.g. 0010 1101 is changed to 1101 0010.

c) add 1, (as you have passed zero) e.g. 1101 0010 + 0000 0001 = 1101 0011

The reverse of the above method can be used to convert 2’s comple- ment negative numbers to their decimal equivalents.

18

3.3 Hexadecimal coding

All machine code programmers do find that any attempt to produce more than just a very few bytes of binary coding is just not practical. Therefore programmers usually use a form of shorthand for describing binary numbers and the commonest system to use is ‘Hexadecimal coding’. (Hex. coding).

In many microcomputer systems the resultant ‘Hex-code’ can be entered via the monitor program directly into the computer, however the 8K monitor program of the ZX-81 does not have this facility so the programmer has either to enter his machine code in decimal numbers, or to write for himself a Hex-loader routine in BASIC.

The principle behind Hex. coding is once again very simple, but it takes a very long time to become fluent in its use, and even programmers of some years experience still have trouble.

To obtain the Hex. code for a 8 bit binary number, the number is split into 2 groups of 4 bits, each group being called a ‘nibble’. A Hex. character is then assigned to represent each ‘nibble’. Hex. characters are the decimal numbers 0-9 and the letters A-F.

The following table shows the different Hex. characters;

Binary Decimal Hex. character 0000 0 0 0001 1 1 0010 2 2 0011 3 3 0100 4 4 0101 5 5 0110 6 6 0111 7 ri 1000 8 8 1001 9 9 1010 10 A 1011 11 B 1100 12 C 1101 13 D 1110 14 = 1111 15 F

A single binary byte is therefore represented by a pair of Hex. characters.

e.g. binary Hex. code 1010 1111 = AF

and 0001 1110 = IE

19

A 2-byte binary number will be represented by 4 Hex. characters.

e.g. binary Hex. Code 1000 1000 0000 1011 = 880B

and 0001 0000 11110101 = 10F5

In the rest of the book 2-byte addresses will be shown as a single group of 4 Hex. characters. The following examples show how a 4 Hex. character number can be converted to a decimal number. Example Hex. to decimal Hex. number = 789A Decimal equivalent= 7 * 4096 = 28672 8* 256= 2048 9* 16= 144 + A* 1= 10

789A = 30874

or if the Hex. characters are taken in pairs: Hex. 78 = 120 ; 120 * 256 = 30720 Hex. 9A = 154;154* 1= 154

= 30874

Appendix iii. is a Decimal-Hex. conversion table and the use of such a table may be quicker and easier than trying to convert numbers by the above method.

20

4. The Z80 Machine Code Instruction Set

4.1 Instructions and data

The stage has now been reached when the actual instructions of the Z80 machine code instruction set can be discussed in turn.

The instructions are divided, in this book, into 18 groups, with each

group containing the instructions that hold a strong resembiance to each other.

This book follows the convention that distinguishes between the actual

instruction, the initial 1-2 bytes, of the instruction line and the data, up to 2 bytes, that if required is placed after the instruction proper. The total number of bytes in an instruction line being therefore 1, 2, 3 or 4.

1.

There are six classes of data that may follow instructions. They are:

A singie byte constant. (+dd) i.e. anumber in the range Hex. 00-FF, decimal 0-255. Instructions that are requred to be followed by a single byte constant have this indicated in their mnemonics by there being a ‘+dd’. e.g. LDA,+dd This instruction loads the A register with a constant held in the next byte.

. A2-byte constant. (+dddd)

i.e. a number in the range Hex. OO00-FFFF, decimal 0-65535. Instructions that are required to be followed by a 2-byte constant have this indicated in their mnemonics by there being a ‘+dddd’. e.g. LD HL,+dddd This instruction loads the HL register pair with the con- stants held in the next 2 bytes. The first byte going into L, and the second going into H.

. A2-byte address. (addr.)

i.e. anumber in the range hex. OO000-FFFF, decimal 0-65535. Instructions that are required to be followed by 2 bytes of data that will be used as an address have this indicated in their mnemonics by there being a ‘adadr.’. e.g. JP addr. This instruction causes an absolute jump to the ‘address’ held in the next 2-bytes. (=GOTO) The first byte holds the low byte of the address and the second byte the high byte of the address.

21

4. Asingle byte displacement constant. (e) i.e. anumber in the range Hex. 00-FF, decimal 128 to + 127, as the number is always considered to be in 2’s complement arithmetic. Instructions that are required to be followed by a single byte displace- ment constant have this indicated in their mnemonics by there being a ‘e. e.g. JRe This instruction causes a ‘relative jump’, the displacement constant indicating the size of the jump. 5. Asingle byte indexing displacement constant. (d) i.e. anumber in the range Hex. 00-FF, decimal 128 to + 127, as the number is always considered to be in 2’s complement arithmetic. Instructions that are required to be followed by a sing!e byte indexing displacement constant have this indicated in their mnemonic by there being a ‘d’. e.g. LD A,(iX+qd) This instruction loads the A register with the contents of the location whose address is formed by the addition of 'd’ to the current value held in the index register pair, IX. 6. A single byte indexing displacement constant AND a single byte constant. (d, +dd) i.e. Two bytes of data each in the range Hex. 00-FF, decimal 128 to + 127 for the first byte and 0-255 for the second byte. Instructions that are required to be followed by two bytes of data for this purpose have this indicated in their mnemonics by there being a ‘d' and a‘+dd’. e.g. LD(IX+d),+dd This instruction loads the constant ‘+dd’ into the location, whose address is formed by the addition of ‘d’ to the cur- rent value held in the index register pair, IX.

4.2 The Instruction Groups

There are many ways in which the hundreds of different machine code instructions could be split into groups. The method chosen in this book is to split the instruction into functional groups, so that the reader can study the instructions in a group and then RUN the BASIC programs from chapter 5 that demonstrate those instructions.

Group 1. The No operation and Return instructions: