You are on page 1of 53
"KOBRAHSOFT™ Pleasant View Hulse Lane, Hulee, Nr. Longton, Stoke-on- Trent, Staffs. S12 SH. ENGLAND, TEL:~ 078 150 5244, Dear Custoner, ‘sany thanks for your valued order for our *SPECTRUN 180, HACHINE CODE COURSE. We hope you will find it interesting and inforaative, We enclose the cosplete course consisting of 12 newsletters and exercises, PLUS a cassette containing our “KDI DISASSERBLER* and "AL ASSEMBLER, which we feel are extresely useful and aust wake our course the best value for woney available! Reseaber, if you get stuck, or if you have any enquiries beut any part of the course, please ring us on the above nuaber, or write to the above address, If you write, PLEASE enclose an SME for our reply. Ke thank you again for buying our course, and we resain, Yours Sincerely, "KOBRAHSOFT SOFTWARE, w KOBRAHSOFT Z80 MACHINE CODE COURSE" CHAPTER (1) Seneral_ Introduction, When you switch on your Spectrue, and prograe it in sic, the following sequence occurs PROGRANNER (Basic Instructions) )>> BASIC INTERPRETER D> Produces Machine Code 9) C.P.U >> Executes Instructions i.e. your Basic instructions are broken down by the Basic Interpreter into Machine Code, which the C.P.U executes to aate Your progran works Let us exanine these ter BASIC INSTRUCTIONS:~ you type these in fron the Keyboard ie, LET Aelj PRINT ‘Hello*, etc. These are aostly sinilar to English BASIC INTERPRETER:-\ this is a progran in your Spectrue which *decodes* your Basic instructions into Machine Code instructions 5 which the C.P.U can *understand*, then execute, t the Central Processing Unit or “brain* of your Spectrum ~ it is the 1808 Microprocessor. As you say * eapect, being an electronic device, it cannot understand English ~ only Hachine Code. Machine Code 1= the Language the C.P.U understands ~ it is sieply a series of electronic signals which represent a series cof ordinary nunbers. The sequence of the nusbers tell the C.P.U what to do. It knows what to do for a certain sequence of nusbers, because it is pre-programed with a set of Hachine Code instructions - there are over 200 for the 160! Points to Noter~ (1), Each Basic instruction has to be decoded into Machine Code by the Basic Interpreter - this tates tise, and is shy prograns written in'Machine Code run upto 60 tines faster than those written in Basic. (2), The Basic Interpreter is contained in a ROM in your Spectrus’s aesory. (3), Menory ~ Your Spectrus can be thought of as having a ‘aesory* consisting of 65535 *boxes* - each *box* can hold a nuaber fron 0 to 255. The values 5535 and 0 to 255 are a characteristic of, and are fixed by, the C.P.U. (4), RON ~ aeans "Read Only Memory" i.e, you can read frow it using PEEK to find the nuaber in a box, but you can’t write to {ty using POKE to,alter it by putting a new musber in a bor. (5), PEEK ~ iF you type PRINT PEEK (nenory location) - this gives the nusber in that location i.e, PRINT PEEK 0 gives 243. the first munber in the ROM. (6). 1F you type POKE location, musber - you can put a new nusber in a bor - but only if it is in the RAN, (7), RAN = This aeans Rendow Access Meaory ~ the rest of your Spectrua’s aeuory apart fron the ROM, The RAN CAN be changed using POKE to put a new nusber in a box. - Wy use Rachine Code?:- Advantages. UD, Faster execution of your prograa, (2), Hore efficient use of aesory. (3), Freedon frow the Operating Syste ise, you can talk directly to the C.P.U. isest- PROGRAMHER >) Machine Code 9) C.P.U 9) Executes progra Disadvantages, (0) Being a 5 Instruction! (2), Tt cannot readily be adapted to other coaputers. (G), Arithaetic calculations are very difficult in Machine Co fs you can inagine, a prograe consisting of a series of nurbers is hard to understand. Thus, the progran can be written in *ASSEMILY LANGUAGE this uses abbreviations or aneaonics (pronounced “MEEMONICS*) to relate the instructions to English Je, {it usesi~ LD ~ aeans LOAD; INC - weans INCREMENT; SUB - aeans SUBTRACT, and so on. The anegonics are entered into 2 progr called an "ASSEMBLER" ~ this then produces the aachine code (nuabers) to be executed by the C.P.U ie. an Asseabler is a convenient way of generating aachine code, Siailarly, the reverse is a *DISASSERBLER’ i.e. it converts aachine code back to Aanenonics for easier understanding of a progran, The’ course now INCLUDES our “KDI DISASSENBLER* AND “KAL ASSEMBLER, aaking it very conprehensive. For FULL details of KDI and KAl, see Chapter bs As stated earlier, sachine code is sinply a sequence of nusbers which represent instructions which the C.P.U can execute. 4s you aay suspect, since the computer is an electronic device, the nuabers are represented by electronic signals. Me can inagine a series of switches ~ these can either be ON (shown by 2 ONE), or OFF (shown by 2 ZERO). in ‘sequence of nusbers, sistakes are easy to sake, one wrong nuaber can give an entirely different a NO) Oe tele) le) ON OFF OFF ON ON ON OFF ON OFF The 160 C.P.U is an EIGHT-BIT device i.e. it groups these ‘switches* together in blocks of eight. Each *switch* is called a BIT. Each group of @ BITS * 1 BYTE or one aesory location or *box*. Incidentally, each group of 4 BITS is called a ‘WIBBLE* (truly!) The above sequence of 1,0,0,1 etc is called the BINARY sequence. Consider again a group of @ bits (=1 BYTE), These bits are nuabered conventionally thust~ 7,4,5,4,3)2,1,0 i.e, each byte has 8 bits nuabered 0 to 7 from right to left (nat 1 to @ as you aight expect). The bits can now be related to numbers using the BINARY systen thus: 7 8 S 4 3 2 4 Oe BIT MuNBER 1m) 6432 18 BA 2A + Decinal Nuaber r, wore siaply, the BINARY systea is based on the nusber 2 (siailarly to the usual DECIMAL systea, which is based on the ‘nuaber 10) i.e, the deciaal nuaber which each bit can represent if * 1 (or is ON or SET, as we say) is the nuaber 2 raised ‘to the power* of the bit nuaber. Take bit nuaber 2, if set ~ this represents the nuaber 212 = 4, Sinilarly, for bit 5 = 212121212 (5 tines) = 32 and so on, Bit 0 is a special case - if it © 0 or OFF (or RESET) ~ it represents 0. If = 1 or ON (or SET) it epresents 1 (since 2 to the power of O= 1 - this is a sathenatical fact ~ don't worry about itl), Thus, we can now sayi~ 7 6 S$ 4 3 2 4 0-BIT NuNBER 12 64 32 16 B42 1 = DECIMAL NUMBER 3210 202 2 2 2 2 2 2 = 210 THE POWER OF 7 6 5 4 3 2 4 O~ BIT NUMBER, ToL ot 4 4 4 f t= AL Bits Ser, 128 4 32 16 B 4 2 = Decinal Nusbers, i.e. the total nuaber the byte can represent is thust- 128+64432+16¢B+4#241=255! Thus, the biggest nuaber that can be represented by @ bits or 1 BYTE is 255. We can take this further ~ consider 2 BYTES. Here we have:~ Cr ee re ee ee Oe ee ieee trav eel 52768 16304 81924096 204802 SIZ 5H Rh = Dein Nos. Add all these together, and you get 68535 - the biggest nuaber which can be represented by 2 bytes. It is iaportant that you understand this BINARY representation, Try counting in BINARY thust~ o 9 0 0 6 0 0 o = 0 0 09 0 0 6 0 Ot Ft 0 0 0 0 0 Oo 1 6 2 oo 0 0 Oo Ot a es oo 0 6 © 1 0 Oo 24 o 0 0 0 0 1 oO 4 #5 OE Oh (ee (sone arn O00 0000 f 1-49 and so on. You aay now see that nuabers are expressed in BINARY according te electrical *suitches* being ON (SET), or OFF (RESET). Thus, we can haver- 0 0 1 1 1 1 1 1 = 63 = CCF Complenent Carry Flag - a sachine code instruction. There are over 200 aachine code instructions which the C.P.U is pre-prograuned to recognise ~ we will send you a List of these later in the course, The Binary systes is also used, since it can readily be related to another nuaber syste called HETADECINAL nuabering, Here, the sequence is based on the nuaber 16, Here, we get:~ o 1 2 3 4 5 6 7 8 9 A Bo DE F 10, B= 11, C= 12, D= 13, E = 14, F = 15, The letters used are siaply a convention. Thus, 19 in Hex, =F. Ml = By We can count further in Hex, thus: F ao Weustis 16TH 6H 34096 =256 Ib Oto ° ° ° Fo = US Decisal) : 4 6 Thus, Heradeciaal, (usually shortened to ‘Hex"), musbers increase in aultiples of 16 i.e. 1bL16 (256), 16IL6E1b (4096), and so on, For exanple, what is 3 in Hex? To calculate this, we divide by the largest of the multiples - here 16 (the nest - 756 is too big), this gives the first digit as 3, with a reeainder of 15. But 15 =F, so 63 = SFH, NOTEL~ AIL Hex nuabers usually have a suffix *H* to show they are in Hex. Thus, here we have SFH, Another exaaple isi~ What is 681 in Hex? Here, we a start by dividing the decieal nuaber by the largest Hex aultiple, which in this case is 256 (16116), This gives a first digit of 2, with a renainder of 149, He now divide the remainder by the next lovest aultiple i.e. 16 - this gives the next digit as 10, with a reaainder of 9. Reseaber, 10 in Hex = A, Thus, the answer ist 681 Decival = ZAYH, The BINARY systee relates to the Wet systen thusi~ EACH NTBBLE (group of 4 BITS) IN A BYTE, REPRESENTS ONE HEX DIGIT. Consider the exaaple 63 above. In BIKARY thsi Byte Nuaber. 0 0 tf Lo Lot tt Binary Hus 128 84 32 16 B42 1 Decinal Nusbers. To rapidly relate to Her, we divide the 8 bits of the byte into 2 nibbles thust- T 6 5 443 2 1 O- Byte Musber, 0 0 Fo AL £4 t= Binary Monber, 0 0 2 448 4 2 1 Decinal Musbers. _ = 3S * BMD © 15 =FH ~ Hex Munber, 2 1 0 Byte Musber 42 t= dectaal Nuabers, 16s 2 1 0~ Byte Rusber. tag 1 1 Y= Binary Nunber, B42 42 1 = Decinal Nusbers, BeAv2e1 = 1S = FH *BHAZeL = 15 = FH ~ Hex Muaber. ier o* F es = FFH = 255 Decinal, Sinilarly, for 2 bytes, the largest nusber is FFFFH = 65535 Deciaal. This siaple way to interchange yetween Binary and Hex is useful, since aost Asseablers and Disassesblers display the vachine code in Hex nuabers. Also, these an now be converted to Binary, 0 you can see the state of each individual bit in the byte, Ihe Structure of the C.PuU. We will now consider in sore detail the structure of the *braint of your Spectrua ~ the Central Processing Unit, We can consider a aachine code progran to be a sequence of instructions for the CPi to perfora particular tasks, In the 10 C.P.U, all instructions are represented internally as single or aultiple bytes. Instructions represented by one byte are called ‘SHORT* instructions longer ones are represented by to or aore bytes. Because the 180 is an @-bit processor, it can nly deal with one byte at & tive ~ if it requires nore than one byte, it aust fetch bytes successively frou neory. Thus, a single byte instruction is usually executed aore rapidly than a 2 or 3 byte one, This is why it is best to write your aachine ode progran using a5 aany single byte instractions as possible, The structure of the 780 can be divided into 5 sain parts ive1- (1), THE CONTROL. UNIT. (2), THE INSTRUCTION REGISTER, (3). THE PROGRAM COUNTER, (2), THE ARITAMETIC = LOBIC: UNIT (A.L.U), (5), THE 24 USER ~ REBISTERS. “) We will now consider each in aore detail:~ THE COMTROL UNIT. ‘The Control Unit is the supervisor for the C.P.U's processing. Its task is to tise and coordinate the input, proc output of any task the C.P.U is perforaing, {HE INSTHUCTION REBISTER, The Instruction Register is where the CPU stores the current instruction which it is about to execute, Reaeaber, your progran is a sequence of instructions, To execute the instructions, the Control Unit aust fetch each instruction in turn froe ‘aesory, and place it in the Instruction Register. THE PROGRAM COUNTER, This 18 a location in the CPU where THE ADORESS OF THE NEIT INSTRUCTION TO BE EXECUTED is stored, ‘THE ARITHMETIC. AND LOBIC UNIT (A. LUD This is the calculator inside the CPU. It can only perfora siaple aritt (adding 1), decresentation (subtracting 1), NOT aultiplication or division! tic, ise, addition, subtraction increaentation {HE USER REGISTERS. ‘ There are 74 user registers in the CPU, They are locations which can hold one byte or two bytes. They are usually shown asi 1 iY The use of the letters is pure convention. The inportant points aret~ The registers AF, BC, HE, and HL are usually paired together. However, they can ALSO be used SEPARATELY as individual registers ise, B, Cy Dy E, Hy and L. When used this, each register can represent B bits or 1 BYTE. When. ‘paired*, they can represent 1b bits or 2 bytes. Also, the arrangesent of letters in the pairs tells us which register holds the high part (i.e, HIGH ORDER BYTE ~ H.0.B), and which the low part (LOW ORDER BYTE - L.0.8). Thus, for exauple, using the Hex uaber 7EEAK, this is 2 bytes reveaber, the H.0.8 is 7EH, the L.0.B is EAH, Thus, if this was contained in the AL register the H register would contain 7EH, the L register EAH. Sisilarly, for AF, BC, and DE - 4,8, and 0 contain the 4.0. contain the L.0.B, Hovever, the AF register pair is a special case. Here, the A and F registers are ALWAYS used SEPARATELY. The A register has a special nase - it is called the ACCUMULATOR, It is alnays used to perfore arithaetic functions. Also, the F register 1s known as the FLAGS register. This is used thusi~ the 8 bits in the byte of the register are used ax *FLAGS*, le, indicators as to whether the result of a certain operation is negative, or positives zero or not zero etc} according to which bits in the byte are SET (+1) or RESET (=0). Thus, the A and F registers are ALWAYS used singly as single 8 dit > registers, each with a special function. The ML register pair is also aore iaportant than the 8C and OE pairs. This is because certain 16 bit arithaetic operations can only be perforaed using HL. Because of this, general register pair operations will usually be faster using the HL register pair ~ use it preferentially where you can! The IX and IY register pairs are also a special case, They are called INDEI REGISTERS ive. they contain an address (ALWAYS 16 bit) to which can be added offsets i.e, U1, IY + 2, etc ~ hence the nane INDEX registers. The CPU also has an ALTEFNATE REGISTER SET. This c be likened to a sirror inage set of the AF, BC, DE and HL registers, They are used aainly as a teaporary storage place for data, which can then readily be put back into the usual registers with a staple ‘exchange* consand, They can thus only be used in eachange ~ there are no separate instructions for thea, There are 3 fore inportant registers - these are:~ THE STACK POINTER (SP). This contains the address of the stack in aesory, The stack is a series of aesory locations (usually in RAM), where the CPU stores nuabers teaporarily. Liten it to the stack used in an office i.e, that aetal spike onto which are placed bills, etc. The only difference being that in the coaputer, it can be thought of as hanging from the ceiling i.e. as the stack grows, it grows DOWNWARD fron HIGH to LOVER aesory locations. It is ALWAYS used as a 1é bit register PAIR, Muabers are stored by PUSHING thea onto the stack, then retrieved by POPPING thea off {see later). Another register is the I Register or Interrupt Vector register, It is usually used to hold the base address of a table of addresses for handling different responses to an interrupt - this is only very rarely used, The final register is the R or Henory Refresh register. This is aainly used for obtaining randoa nuabers froe 0 to 255, We hope you have understood the isportant points in this first part of the 280 course. To help, please find on a separate sheet a few exercises to try - the answers are on the reverse side - no peeking! w KOBRANSUFT Z80_ MACHINE ODE COURSE” cuar 1) EXERCISES: We hope these feu exercises will help to illustrate the points dealt with in the first chapter of our 180 course, We suggest you try then, then check with the answers which we have printed on the opposite side, Also, auke a few of your own = the sere practice you get the easier it will becone, Reneaber, it you get stuck, or if you have any questions about any part ‘of this course, don’t hesitate to write to us. PLEASE enclose an S.A.E. for our reply! (A), What are the following Decinal nuabers expressed in BINARY notation? mea a a, 88, wa (27, (B), Hhat are the following Decisal quaber s expressed tn HEX notation? (1, mW. mM, 2, . 98, (3), 78, Fee the answers, see overleat ~ no peeping! aw “KOBRAHSOFT Z80 MACHINE CODE COURSE” CHAPTER (2) USING THE REBISTERS. We will now consider the use of the REGISTERS in aachine code, by considering a fev sinple aachine code instructions i.e, LD HLynn, These are the anenonics* (rereaber?) fors~ "Load the HL register pair with the 2 byte nusber represented by nn’, The aachine code instructions are:~ Tn DECIMLE S3ynyn or 33ynL snk In HEE 4 2bynyn or 2H ynL nie sot as you aight have expected:~ 35,nlljal; where ot ix the HIGH ORDER BYTE (the larger part of the nuaber), and aL is the LOW ORDER BYTE (the sealler part of the nunber) e.g, for the Hex nuaber 7006 ~ 7D is the H.0.B, 06 or 6 ts the L.O.B. AS you can see, this is a THREE BYTE instruction i.e, 33 (the instruction to LOAD HL with a 2 byte nuber) - the nusber consisting of the 2 bytes that follow i.e. nyn or wore specifically, nlyoH. The nusbers are nlynH and NOT lyn as you would expect, because: IM THE 760 CPU, NUMBERS ARE STORED LOM BYTE FIRST, HIGH BYTE SECOND! i.e. the reverse to what you would expect. This ts slaply a convention, but it is MOST IMPORTANT. Thus, for the Hex nunber 7008, we would haves~ eHow 180 INSTRUCTIONS LD HL, 7006 13864125 ~ in DECIMAL, LO HL, 7006 21,6470 ~ in Hex. This is how the instruction MUST be entered in a wachine code prograa. When executed, the result will giver H Register 1 Register In Hex » 6 {.e. the result you wanted. YOU aust enter the correct instruction sequence so that the result is to be what you want. Consider, {¥ you had writtens~ Cin Hex} 71,70,06 ~ you would get as a results H Register LL Register % 2 fost inportant that you understand how to enter nuabers as 180 instructions arly:~ (Un Hex) for the nuaber 7006:~ = the reverse to what you wanted! It i correctly, to get the result you want. Si MENONIES 180 INSTRUCTIONS U0 Benn AyoLynH OR 146,70 - gives 8705 C=06, U0 Deon H1ynlyndl OR 11,4470 = gives U=70; E06. We will now write our FIRST aachine code progran to show you how fast it really is! A good exaaple uses the LOIR cousand, which aoves blocks of aenory around. We will discuss this in greater detail later. We will load the SCREEKE (code for the picture) foe any of your games to a convenient location; e.g, 32000 (7000 Hex)y then use the LDIR consané to aove ALL 6912 bytes into the screen area at 16384 (4000 Hex). Firstly, choose a gae with 2 good picture ~ we willl use for our exaaple “EEPLODING FIST*, ANY picture will do ~ but ensure that it is suitable i.e. it loads at noraal speed, and is not ‘protecte the Melbourne House ganes are good in this respect. To check, type LOADP*CODE 14584 (ENTER) and PLAY the qane tape fro the start. Usually the Basic loader appears first, then in a suitable gane, the SOREENS should then load to give you a picture, Now, load the picture to 32000 by typing LOAD'*CODE 52000 (ENTER). Instead of a picture now, the SCREENS code will sinply load ‘to address 32000, He can put our aachine code progran at, say, 30000. The anesonics for the progran are:~ enone 180 INSTRUCTIONS (Hes) 180 INSTRUCTIONS (Deci Lo HL, 7000 21,070 330,125 U0 DE 4000 11,040 17,0,54 LD BC, 1800 1,0)18 1,0,27 Lor £0.80 231,178 RET 0 m1 ists the progran consists of the sequence:~ 33,0,125,17,0;64,140,27,257)176,201 ~ only 12 nuabers! The HL register contains the start address of the block to be soved ~ here = 7000 Hex = 32000 Dec. The DE register contains the éestination address ~ here * 4000H = 18384 Dec. The BC register contains the nuaber of bytes to be aoved - here = 6912 Dec = 1800 Her, The instruction for LOIR are the nusbers ED, BO Hex = 257,176 Dec. The RET or Return ensures we return to Basic. The instruction for RETurn is CY Hex = 201 Dec. We can PORE the 12 nuabers for the routine starting at 30000 using the following Basic Loader (MOTE: This could also be done using an ASSEMBLER - see earlier). Type int- 10: FOR A$0000 TO 30011 INPUT By POKE A,B: NEXT A This progran waits for you to input a nuaber, then POKES it to the appropriate address. RUN it, and enter the 12 nuabers, Your first aachine code progras now resides at address 30000 - JOOL1. If you wish to exanine a range of aesory locations, we will use the following prograe (ve shall call it *PEEK LINE (2) Type 10 (ENTER) to remove the previous progran, then type int= 10: FOR A=30000 TD 30011: PRINT Ays PRINT PEEK As NEXT A UN it, and you will see your aachine code progran! How do we execute this progran? All aachine code routines can be executed troa Basic using the USK command. So here, we type RAKDOMISE USR 30000 (ENTER), On pressing ENTER, the whole picture (6912 bytes) is aoved froa address $2000 to the screen in a Flash! Such is the speed of aachive code! If you want to repeat the routine to inpress your friends, type 10 (ENTER) to reaove “PEEK LINE*, then enter this seall Basic prograst~ 101 RANOONISE USR 30000 20: 6010 20 RUN ity and the picture will appear in a flash! Line 20 stops the conputer fros printing the usual *0.K.* aessage at the bottos of the screen, and spoiling the picture. To re-run the program, press “BREAK*; type CLS CENTER) then type RUN (ENTER) again, and so on. This illustrates the beauty of aachine code - whilst ruaning your aachine code routine, YOU are in TOTAL control of the computer, not the reverse! But REMEMBER, ONE wrong nuaber can give the CPU a coapletely different instruction fron the one you intended, which usually *CRASHES* the coaputer. This is siaply the tera used when there is no response frou the teyboard ~ don’t worry, no danage is done! It is siaply resolved by switching your coaputer off, then (after a fi seconds) on again - or by pressing the RESET switch if you have one. This is said to RESET the computer, or start it anew Incidentally, this can also be done (if you have keyboard response and wish to reset the computer) by typing RANDOMISE USR 0 (ENTER), This calls the ROM routine at address 0, and resets your computer - just as if you were switching it on in the sorning. THE STACK AMD STACK POINTER (5.P.). ‘As stated earlier, the stack is an area of aesory which the CPU uses for the teaporary storage of nusbers, The Stack Pointer (S.P.} is a 2 byte register which contains the current adéress of the last nuaber on the stack, Liken it to that office "spike" on which you stick bills, etc. However, in the Spectrua, the spike can be inagined to *hang fron the ceiling’, thus: CEILING or Top of Meaory Top of Stack Stack Pointer Botton of Stack = address of last nuaber, Lover aenory ise, it grows Gonnwards (towards lover wenory). A ousber is saved onto the stack using the PUSH instruction, It is retrieved using the FOP instruction, ALL quabers saved on the stack are 2 byte nuabers i.e. you CAN have PUSH ML - save the value contained in the HL register on the stack. You CANNOT have PUSH D ~ save the contents of a single register. Can you see that shen you PUSH a nuaber onto the stack, the address of the S.P, DECREASES by 2 bytes? (i.e. SP=SP-2), Sinilarly, a POP INCREASES §.P, by 2 bytes (SPH5P42), PUSH and FOP are a quick way to exchange nuabers between registers i.e. if you PUSH HL, then POP DE, the ouaber in HL is transferred to DE! You MUST always know the location of the stack in aeuory. If you overurite the stack (ive. load other bytes over it), the Spectrue will crash, since the CPU won't know where its next nuaber will cone froa! The position of the stack is fixed from Basic using the CLEAR instruction i.e. CLEAR 0000 aeans the stack starts at 59999 (CLEAR value - 1). In aachine code it is fixed using the LD SP,nn instruction, Where nn is the 2 byte address you choose. Reseaber, you aust alnays REVERSE your sequence of PUSHeS. and POPS to retrieve the correct muabers you need i. PUSH AF PUSH BE PUSH HL reversed givest~ . POP HL Por aC POP AF = to retrieve the original values. USING THE RESISTERS 10 ADDRESS MEMORY. ‘There are FIVE wain ways in which data can be transferred frou one register to another, or frou a register to aesory i.e.t~ (11, Innediate addressing. (2), Register addressing. (3), Register indirect addressing, (4), Extended addressing, (5), Indexed addressing. a Don't worry too auch about the complex nanes - these are only used as a convention, Taking each one in turn: INMEDIATE_ADORESSI The general fore for this isi~ LD ryn (or other instruction, we are using LD as an exaaple only), Where ris any S-bit (single byte) register e.g. A\HyL etc, and n is any 8-bit (single byte) nunber e.g. 0- 255. We thus have an interaction between a REGISTER and DATA, An exanple is:~ LD A,255 (Dec.) or LD AyFF (Hex). The aachine code instructions are: 62,255 (ec) or SE,FF (Hex). Note that the actual data is a part of the instruction - this aeans that the CPU can execute the instruction IMMEDIATELY - it doesn't need to look in aewory to find sore inforaation in order to perfore the instruction. The general foraat ist~ Ist Byte:~ instruction code (or opcode) ~ this tells the coaputer what the instruction is i.e. LD A; LD Hj ttc, nd Byter~ the actual data byte. Since this is a single byte ~ only nusbers in the range 0-255 can be used, REGISTER ADDRESSING, The general forn is:~ LD rr. (or other instructions) ~ i.e, an exchange between one register and another. An exasple ist WAL; or LO HE etc, NOTE:~ We CANNOT have LO H\F ~ since F the FLAB register is a special case (see earlier). The instruction LO HE weans LOAD H with the contents of E, Thus if M contains 7D (Hex) and E contains JF (Hex), After execution of the instruction we would have:~ H contains SF, and E contains 3F, These instructions only need ONE byte, thus they are fast and are to be used wherever possible. REGISTER INDIRECT ADDRESSING. This sode is @ Tittle aore conplex. The general forsat is:~ LD (rr),A or LD Ay(re) or LD (HL),n. Here we have the transfer of data between the CPU and a sesory location whose address is contained in a L6-bit (2 byte) register pair i.e. HL, DE ete, WOTEN~ rr is used to show such a REGISTER PAIR. Consider: LD (rr},A, Suppose rr is the HL register pair, and it contains the ‘aber 7000H (the suffix *H" frow now on will indicate a MEX nuaber'~ no suffix will indicate a Decieal nuabery this is the usual convention used! Suppose the Accuaulator A contains the nuaber TEM, The instruction LD (HL),A aeans take the value in Ay and put it into the address contained in HL. Thus, after execution, the location 70004 mould contain 7EH, HL would still contain 7D00H, and A TEH, For LD Ay rr) ~ suppose rr was HL, which contained 7FOOH; if location 7FOOH contained the nuaber 4H, and A contained 63H - after execution, A would contain 4AH, For the exasple:~ LD (HL) a. Suppose HL held the nusber G000H and n {a single byte nusber) was ADH. If the location 8000H contained, say, 20K; after execution it would contain 4D4, This fede of addressing is faster than ordinary indirect addressing, since the CPU need not fetch the address fron aescey. EXTENDED ADDRESSING. The general foraat ist LDA, fond or LD (nm) A ort LD HLytnn) or UD (nn) HL where nn represents a 2 byte ({b-bit) address in sesory. In this ode, the instructions roe the prograe supply the CPU with an adress specified by these 2 bytes. V single registers ive, AyD etc are involved, there will be 3 instructions, With register pairs e.g. HL,DE etc, there will be 4 instructions. Exgs Consider: UD Ay(on) ~ the general instruction foreat ist- 3AynL,nH. LD Urn) A ~ the general instruction format ist- 32)nL,n4, LO HLy (nnd ~ the generat instruction forsat ist~ ED,6B,0L aH. UD (nn) HL ~ the general instruction foraat ist~ ED,63,nL,0H, or, in general, Byte It- Opcode - tells the CPU what type of instruction to expect. Byte 2:~ Possible additional opcode if register pairs are involved. Byte 3:- Low order byte of the 2 byte address, Byte 4:~ High order byte of the 2 byte address, {NDETED ADDRESSING, This; as you it expecty involves the use of the Index Registers IX and IY. The general foraat ist- LD ry (114M) or LO ry (IVA) oF LD (1148) sr or LD IYHBD re Where ris a single byte register e.g. AyB,H,D etc; d is a single byte uaber for the displacesent froe the start address. The CFU adds this nuaber ¢ to the contents of the IT or IY register to find the required adéress. One typical usage for this type of addressing technique is the aanipulation of tables of data. e.g, you can set the address in the II or IY registers to be the start address of a table of data. You can then specify any particular byte to which you want by adding the value d, “ ea UD Tt, TABLESTART i) This will refer to the Sth byte fron the start of the table, and it will be placed in the Accuaulator. ‘The general foreat is:- Byte 11- opcode ~ tells the CPU what type of instruction, Byte 2:- opcode ~ as above, Byte S:- displacesent 4, Indereé addressing is slow because the CPU aust gerfora an addition in order to obtain the effective address. However, it is very flexible since the sane instruction can refer to all the elesents in a table sinply by altering the value of 6. NOTE:~ You can combine inediate addressing (i.e. specifying the nuaber you want loaded) with external addressing (ists specifying the address to be loaded by using a register pair). This is called “IMMEDIATE EITERNAL ADDRESSING. Unfortunately, you can only use the HL register pair and the general foraat is thus:~ LD (HL),n. This is very useful, since it allows you to directly 4i1 a aeaory location with a nuaber without having to load the nuaber into a register. Considers if HL contains the address 7000H, with the instruction LD (HL),FFH, you can put the value FFH in address 700H! The instruction is only 2 bytes Tong i.e. 3éHyn. Where n is a single byte nuaber. A sisilar coabination is possible using the Index Registers 1 and IY. This is called "IMMEDIATE INDEIED ADDRESSING. The instructions tate the fore of: to Ute ya Lo vd THE FLABS RESISTER F. ‘swe stated earlier, the F or *FLASS* register is used to indicate the existence of certain conditions. The Flag register is an B-bit register and, of the @ bits, 6 are used as *flags'. These are as followsi~ Bit Noe 7 ‘ 5 4 3 2 1 ° FLAG i= SIGN © 7ERO.—NOT HALF NOT PARITY NEGATE CARRY FLAB FLAG USED. CARRY USED. andor FLAS (3) a FLAG OVERFLOW SUBTRACT (C) tH) FLAG FLAS. Cn) NOTE: These flags all relate to the condition of the quaber in the A register (Accuaulator), We shall briefly discuss lag in turn = we will discuss their uses aore fully later. THE TRO (2) FLAG, This flag will be set i.e. the bit which represents the flag (bit 6) will be set or = 1 if, asa result of an arithaetic operation, the contents of the A register are zeroj otherwise it is reset or « 0, ‘WE SIGN FLAG (5). This is very siailar in use to the zero flag above i.e, if the contents of A are positive - the flag is sety if negative it is reset. THE CARRY FLA, This 13 one of the aost iaportant of the flags. Briefly, it is set if the result of an arithaetical operation would give an ‘underflon* i.e, 200-201 gives 255! This is best seen by thinking of the carry bit as a 9th bit of the A register thusi~ Nusber Carry Bit Nunber in Binary Fora 200 - 11001000 +201 - = 1001004 255 1 (set eeeeee! A sisilar situation arises with an overflow" i.e, 1324135267 with the carry set. PARITY/OVERFLOW FLAB (P/V) This flag 1s set when, after an arithaetic operation, there are an EVEN nuaber of SET bits in the result. SUBTRACTION OR NEGATE FLAS_(W). This flag 1s set if the last operation was a subtraction, HALF-CARRY FLAB (HD. This {lag is set sinilarly to the carry Flag, but only if the overflow occurs fro the Sth bit ~ not the tht ow for the good news ~ no exercises this week! Me think this chapter should keep you thinking for a whilel aw "KOBRAHSOFT Z80 MACHINE CODE COURSE” CHAPTER (3) This aonth we give you a List of the MORE COMMON 280 anesonics and their representations in Hex nuabers, Do not worry 4 you don't understand thea - we will deal with each group in aore detail later. EHONTC ven vo enon ex wo mMenONTE HEL WO mKEHOMIC ver WO 0c HBC oa Wo A x Lo Dyan D2 aeee SUB % AOC HL DE DSA ve Bt 03 UY, (A00R) FD ZA rx xx YOR A a AC HLS 7A INC DE 1B LD Yon FOU xnxx YOR fu ADD AS(HLD 86 WE HL B Win ux ADD A\UTAdis) DD 86 ax We 11 00 23 UD §P,(a00R) ED 7B ax ax ADD ASCIYAGis) FD 8b xx Wwe tv Fo 75 U0 SPynn Mor ADD Ayn Cha INC §P B U0 SPH 9 ADD HL, BC 4 ice BA U0 ser oo FP AOD ML, DE w INR & R2 10 SP)1Y Fo Fo 00 HL HL n JP URL 8 Lon 0 AB ADD HL, SP ¥ wm) me9 oor eo 8 aon 11,8 mov a aa0R 03 wn ne 1 0 Ao 00 11,08 py JP CyADOR DA vx xe Lore 0 0 Ao 14,11 m2 JP NC,ADOR D2 ax ax oR (HL) Bb 00 11,88 ma JP NUADDR C2 xx Hx RA 37 Ao 1Y,BC FD 09 2? LADIR Chan ax mn Fou #00 1Y,0E roy 2 Cydis Wor ove cD BB a0 1, 1Y a 2 dis 18 x one eS An 1,8? 3 IR NC dis. Dn OUT Cha 079 AND CHL ” IR NI, dis max OUT port,A D3 port. aD A 7 AR Ldis Bx POP AF FL AND fm UD (ADDR)A 32 a ee PoP Bt ct BIT OA 0347 U0 (DDR) BC ED AS ax wx POP DE m0 CALL ADDR Carer LD (ADDR),DE ED SS xx xx POP HL a CALL C\ADDR DC ax ax UD (ADDR) HL 22 ay ax POP IY 0D et CALL NCAADOR D4 ax xx 0 (a0) ,4 0 Por ty roel CALL NT,ADOR Ch ax ex Lo (06,4 2 PUSH AF 5 CALL 2,ADDR CE ax xx HLA 0 PUSH BC os cP ca U0 HO, bax PUSH DE 05 A iF (0 1dis),A 0077 a PUSH HL 5 on Fea (0 (1edis)n 00 3 xx ax PUSH IT oo 5 Por ay UAH SA a a PUSH TY Foes cre fo 81 Un at) o* RES 044 ce a7 vec HL) B Uae " RET 9 et A » ay tH % RET C 08 DEC BC 08 UD As(edis) 0D TE ax RET NC 0 DEC DE 8 Ud Ayn eon RET NT co eC 2B LD By Ob ax RET 08 Dec 1 00 28 UD BC, (00RD Bax ex RL A 817 vec 1Y a LD BCom OL a ex RRA ce AF ee SP B Lyn Of a RST 08 oF o FS (0 Dn tbo SBC RL BC ea DIN dis 10 x8 LODE, (ADDR) ED SB xx ax SBC HL,DE ce a fe U0 Denn om SSBC HL HL 82 ELIS ES En HE x 58 HLS? on ELAR 08 UW Ha 2 04 StF 3 EL DE, AL & (HL, aDDR 2A ae a SET OA coo IN Ayport 0B xx U0 Hyon 2 StAA cB 27 we 0) u (WO 1Y, (00RD ZA ax ax RA co a We aust stress that this is not a FULL List ~ for the full List, please consult any of the 100 reference works which are usually available at your local library. A good book we can recomsend is:- *PROGRARNING THE 780* by Rodnay Zaks. This gives a FULL List of ALL the 180 anesonics, together with a Lot of other useful inforaation. NOTE: In the above li: ‘n= represents a SINGLE BYTE nuaber. ‘in ~ represents a TWO BYTE nuaber, x4 ~ represents a SINGLE BYTE nuaber (2 Hex digits). ux x4 ~ represents a TNO BYTE nuaber (4 Hex digits). Inioraation Representation in the Spectrus As we stated earlier, all inforaation in your Spectrua is stored as groups of BITS, A BIT stands for Binary éiglT ise, @ "0" of a *1*, Because of its electronic nature, your Spectrux can only represent data using this two-state or BINARY systea, Just to renind you, the rules for ADDINE binary nuabers are: where (1) denotes a ‘carry* of 1 i.e. 50100 (4 decinall As stated earlier, we can thus represent auabers fro 00000000 to LILJL111 i.e, 0 to 255 in 6 bits in binary. There are 2 probleas here: (1) we are only representing POSITIVE numbers. (2) The aagnitude of these quabers is linited to 255 if we use only 8 bits, Consider each of these probleas in tu SUGNED BINARY. In a signed binary representation, the left-aost bit is used to indicate the sign of the nuaber. AS a convention, *0° is used to denote a POSITIVE nusber, while *1* is used to denote a NEGATIVE nunber. Nowy 1ILLNL11 will represent ~127, while OLATIILL will represent #127, He can now represent positive and negative nuabers, but we have reduced the aaxiaua range to 127, e.g. 06000001 represents +1 (the leading 0 weans ***, followed by 0000001 = 1), Also, 10000001 is -1 (the Leading *I* seans *-", followed by 0000001 = 1), Wow consider the MAGNITUDE probles. In order to represent larger nuabers, we will have to use a larger nusber of bits e.g. if we use 16 bits (2 bytes), we can represent nuabers fron 32768 to #32768 in signed binary, Bit 1S is used for the sign, and the renaining 15 bits (14 to 0) are used for the aagnitude. Consider using signed binary for a siaple addition i.est~ let us add ~S and 47:- 47 ist~ 00000111 “5 isi~ 10000101 The sua ist- 0001100 or ~12! This is incorrect! It should be +2! i.e. the binary addition of signed nuabers does not work correctly. The solution ‘to this problea is called the *tno's complesent* systea, which will be used instead of the signed binary systea. In order to introduce two's coaplesent, let us first introduce an interaediate step:~ one's coapleaent, ‘te’s Conplenent. Tn this systen, all positive integers (whole ausbers) are represented in their correct binary foreat, For exanple, #3 is represented a5 usual by 00000011. However, its complesent -3 is obtained by compleaenting or swapping every bit in the original representation i.e, each 0 is transforaed into a 1, and each 1 is transforaed into a 0. Thus, in this exanple, the one's coapleaent representation of -5 will be 11111100, Also, #2 is 00000010; -2 is LIIULIOL, Note that here, positive nuabers start with 2 0 on the left, segative with a 1 on the left. fs a check, let us add sinus 4 and plus 6: o 4 isi- LHNIONL #6 tst~ 00000110 The sum ist= (1) 06000001 where (1) indicates a carry, The correct result is 2 or 00000010, i.e, it did not work, This is overcone usingt= ent, In this systen, positive nusbers are still shown, as usual, in signed binary, just as in one’s cosplesent. the difference lies in the representation of NEGATIVE nusbers. A negative nusber in two's coaplesent is obtained by First computing the one’s Couplenent, and then ADDING ONE. Consider:~ 43 is shown in signed binary by 00000011. It's one’s coaplesent is 11111100, The two's conplewent is this PLUS I or IITLI101. Consider:- 3 ist 00000011 45 ist~ 00000101, = G0001600 The result is correct! i.e, we have found a way to represent negative nuabers - we now know how to use this convention if we wish to enter nusbers of specific sign for arithsetical calculations, ete. USING THE HwENONICS, We will nom consider the use of the various groups of anesonics in aachine code prograas, As we sentioned earlier, all tachine code prograns are called frou Basic using the *USR" comaand. This can take the fore of RANDOMIZE USR, PRIMT USR RUN USR etc. PRINT USR is a special case, since, on returning to Basic from a sachine code routine it prints the value in the fC register pair at that tise, Uhen the Spectron operating systen encounters this *USR* function, it loads the BC register pair with the muaber specified in the USR command, We can check this thust~ Types POKE 32000,201 (ENTER). Now type PRINT USP £32000 (ENTER). The usher 32000 appears. You have executed another aachine code progran. It works thusi~ when you PO‘E the value 201 to address 32000 - this is the anesonic for RETurn i.e. return to Basic. (See list abovel. Typing the PRINT USR 32000 consand loads 32000 into the BC register pair ~ this is printed on returning to Basic! A further refineaent vould bei~ POKE 32000,14} POKE $2001,740; POKE 32002,201, These nusbers represent the sathine code progras: 6,240 RET Thus, type PRINT USR 32000. The nusber 32240 appears! This is because you have loaded the C register with 240 (FOH) - the B register is unaltered - thus the new nuaber in BC is 37000 + 240 = 32240, Experiaent by putting various other nuabers in the Cregister i.e, change the nuaber at 52001, and note the results, Reseaber, you HUST always include a PETurn, otherwise. you Wil not return to Basic and the coeputer will crash! Another exaaple of an B bit loading instruction ist WA ‘This would read asi ‘Load the A (Accuaulator) register with the contents of the B register". We can have sisilar instructions involving the other registers i.e, LD CyAs LD EH etc ~ even LD A,A! Reneaber, the F or Flags register is a special case, so there are no instructions involving it singly e.g. LD F,A is not peraitted. A general representation of this type of instruction is:~ Wry = where r represents any @ bit register EXCEP! F. Reneaber, this is called REGISTER ADDRESSING (see earlier) or the transfer of inforaation trou one register to another. We can also load nusbers into a register, e Uo 0,074 + where this load the D register with the nusber D7 in Hex’, (215 deciaal). The nusber for the anesonie LD O,n oF LOD with a nusber, is 18H, followed by the nusbers or 1b,n. Thus, the instruction for LD D,D7H isi~ 14H,07H or 22,215 in deciaal. This would put the nunber 215 into the D register. a You aay recall this is known as inaediate addressing. Again, you can do this with any of the registers, with any nusbers ~ the Linitation of course being the size of the nuabers i.e, 0-255 since you have only 8 bits. A shorthand representation of this ist= Wry where r indicates any register and a any SINGLE BYTE uaber. te now need to know how to put suabers into aeaory locations ~ after all, we have only so aany registers! The general smenonic to do this is:~ LD Ayton Reneaber that the brackets aan ‘*the contents of the location pointed to by the nusber an*, Where na is a TWO BYTE (16 bit) husber. Let us clarify this, as it is a difficult concept, but one which it is aost iaportant that you understand clearly, Suppose the usber is, for exaaple, 32000 (7D00H). Thus, we haver~ LD A, (7D00H) Suppose location 32000 contained the nuaber 200; then the above instruction mould result in the nuaber 200 being placed A register. Other points to note about this instruction are: (11, You can only use it with the A register. (2), YOU aust supply the wenory location as a 2 byte (16 bit) auaber, The reverse instruction is also valid i. LD Inn Here, the ouaber in the A register is placed in the nesory location addressed by the nuaber na- in the above case, if A contained the nuaber 175, the instruction would result in this quaber being placed in location 32000, Reneaber, these 2 instructions only apply to the A register - there are other instructions for the other registers, but fone quite as clear as these, Again, its because A is a special register (the Accumulator), ‘As you can see, these 2 instructions are very powerful. The instruction LO A, (nn) allows us to get a nuaber froa any aesory location, and place it in the A register. The instruction LD (on),A allows us to put a nusber in any aesory location (row the A register. ‘Another fora of instruction uses register indirect addressing. These are of the general fora:~ 1 rt Lo Ay (aC) Uo 4,08 Load the register r with the contents of the wesory location pointed to by HL*. “Load A with the contents of the aesory location pointed to by ‘Load A with the contents of the aesory location pointed to by DE Note that by using the ML register pair as the pointer to our aeaory location, we can load to ANY register ; even Hor L = bout using 6 or DE, we can only load into the Accuaulator, This is because the HL register pair the favoured register pair in the sane way that the A register is the favoured single register. Again, the reverse instructions apply i.e.t- LD HL),ty UD (HC) ,Ay LD (DED A Alternatively, we could use the index registers IX and IY to point to the Wo rca) Wr ed Here, ris again any register, and d is the displacesent frou the address pointed to by IK or IY. MOTE: This is a single byte nuaber d- NOT the D register. It is usually used for addressing tables containing lists of data, The reverse instructions also apply tve.t- LD (IX+6),r5 LD (IV+d)r. We can also have Imsediate External Addressing of the forai~ UD (WL Unfortunately, this ONLY uses HL, With the index registers, we can have Iauediate Indexed Addressing of the fora1- LD (1404) yh and LD (1Y+8) Now, please try the exaaples to see if you have understood this chapter. These read ast ory location i.e, a "KOBRAHSOFT Z80 MACHINE CODE COURSE” CHAPTER (3) EXERCISES UD, What is +15 in Signed Binary? (2), What is 465 in Signed Binary? (3), What is -27 in Signed Binary? (4), What is -110 in Signed Binary? (51, What is #7 in 1s Complesent? (8): What is 65 in 1's Complenent? (71, What is ~42 in 2°s Complesent? Answers overleaf! a ssi, (01, seer = 6900111 (2), dnseer = 010000. (3), dsr 100H011 (0), Ansver in101110. (5), Answer = 00000111. (6), Answer = 10111110, (7), Here, #42 in 1°s Conplenent is Coupletent, we aust add 1 ives: 90101010. Complesenting to get the negative nuaber givest- 11010101. To get the 2's 1010101 + 00000001 = the answer, w KOBRAHSOFT Z80 MACHINE CODE COURSE" CHAPTER (4) We continue this onth by exanining the use of aore groups of aneonics. The next being:= structions arei~ INC r = where r is a single byte (8-bit register). ec r INC rr = where rr is a 2 byte (16-bit REBISTER PAIR). DEC rr IWC is short for INCRENENT or "increase the value by ONE; DEC is short for DECKENENT or "decrease the value by ONE", Note, again, how the register containing an G-bit nusber is represented by a SINGLE letter, while the register containing a 16-bit rubber is represented by THO letters. This is the standard convention which you will find over and over again. Thus, we can haves IWC Hy INC Dy INC Ay INE Ly INC E, INC B ete. TNC HL, INC DE, INC 8C, INC IY, INC I ete. In each case, the aeaning is Increase the value of the nusber in the register or register pair by ONE", Thus, if the H register contained, say, SSH (85 decinal)y after executing the INC H instruction, it would contain S6H (G6 Decinall. ‘Suppose the register pair DE contained the nusber 2FAZH (can you convert this to decieal? ~ it is in fact 12194 Deciaal) - fon executing an INC DE instruction, it would contain 2FAIM (12195 Decimal), MOTE that with a register pair and the corresponding 14-bit muaber, the LOW ORDER BYTE is incresented ONLY i.e. the byte in the L Register. Sinilarly, we can also have:~ DEC H, TEC D, DEC A, DEC L, OEC E, DEC B ete DEC ML, DEC DE, DEC BC, DEC IY, DEC IX etc. where the meaning is "Decrease the value of the nusber in the register or register pair by ONE". Using the above exzaples, Af the M register contained 554 (85 Decieal); after executing the DEC H instruction, it would contain SAH (84 Deciaal), Again, for the DE register pair, if it contained 2FA2M (12194 Decinal); after the DEC DE instruction it would contain ‘FAI 12195 Decinal, We can also increase the value of any ory location, using an instruction such ast~ Ne HU) REMEMBER - this has a totally different weaning frow INC HL. The instruction INC (HL) aeans ‘Increase the value of the tusber contained in the location in ML by ONE, This, if ML contained SBOOH (22528 Decieal), and suppose the location S800H contained the nuaber 15H (21 Decinal?; after the instruction INC (HL), HL would STILL contain SBOOH, but the MEMORY LOCATION ‘SBO0H would NOW contain 16H (22 Decival}. A shorter way of stating this is * Increase the contents of the sesory location pointed to ty HL by one* i.e, the brackets in INC (HL) mean ‘the CONTENIS of the aegory location contained in HL". NOTE: While TNC HL acts on the 16-bit muaber in HL, INC (HL) acts on the B-bit nuaber stored in the location contsined in the ML register pair. Sin{larly, we can also have: Dec (HLY = with the same meaning, only DECREASING the value, We can also have, for the Index Register: IW X89 INC (148) ~ where # is the displacenent DEC (1¥4d) frou the start address. DEC (1¥+d) NOTE:~ ONLY INCrease and DECrease operations on G-bit nuabers affect the FLAGS. The saee operations on 16-bit nuabers DOES WOT AFFECT THE FLAS, a Since the Flags are affected when B-bit quabers are involved, we will now review the operation of the (1agsi- This flag will be SET (= 1), if bit 7 of the B-bit RESULT is 1, This flag will be SET (= 1), if the bit RESULT is ZERO. HALF-CARRY FLAG:~ This fag will be SET (= 11, if there is a CARRY INTO, or a BORROW FROM bit 4 of the B-bit 20) for “INC and NEGATE FLAG:~ This flag is SET (= 1), if the last instruction was a subtraction, Thus, it is NOT SET (i. - SED (= 1), for “DEC. SINGLE BYTE (@-BIT)_ARITHNET We give below a table of the operations for S-bit arithaetic. As you will see, these are of THREE aain typ SUBTRACTING and COMPARING: #0016, ANEMONIC Wo, OF BYTES TINE TAKEN EFFECT OM THE FLAGS craw Ss NW AOD Ayregister 1 4 ete teat ae ‘AD Aynusber 2 7 raerrodr #00 A, (HL) 1 id te tele ADD Ay (1ded) 3 9 Ree teeta AOD A, Yea) 3 " Paropod AOC Ayregister 1 4 Tete tee #00 A,muaber 2 7 Pirrod AOC Ay CHL 1 7 rir rod AOC A, tea 3 1” rrr pod AOC Ay UUYe8) 3 9 parro0d SU register 1 4 braorad 508 ruster 2 1 praoxrid Sub (HL) 1 i etl 8U6 1149) 3 " ete ie ie SUB (IY+A) 3 1" praeorad SOC Ayregister 1 4 preurid S2C Aymunber 2 7 ee tei ' SBC A, (HL 1 1 prerik SHC A, CtH8) 3 9 ete SHC Ay (148) 3 9 ete CP register 1 4 reeonrae CP nusber 2 J rreorik ce WL 1 7 rerpie Ch cid 3 9 praeorad ce nea 3 9 reeorad NOTE: Here, the Flags notation represents: X= indicates flag is altered by the operation. 0 = indicates flag is set to 0 (RESET). 1 ~ indicates flag is set to 1 (SED. The tine taken is expressed in ‘T* States, where 1 ‘T* State = 0.5 aillionths of a second! o The point to reseaber is thats ALL O-bit arithnetic operations aust be perforaed using the A Register (Accusulater). This is Lucha strong convention in 780 aachine code snevonics, that the abbreviation *A* is even onitted in sone aneucnics. That” is, to wubtract “BY frow *A*, we would expect to seer SUB AB = whereas we actually find: sue 8 Respite this lisitation on all arithaetical Instructions being restricted to the A register, the 180 language is still very versatile in what we can actually add to whatever nusber we have in the Accuaulator i.e. we can have:~ ADD Ayr - Add any single register to A, ADD Ayn = Add any B-bit nusber to A, ADD A,IHL) - Add the B-bit muaber in the location whose address is in HL. AD A\CIX+d) = Add the G-bit nuaber in the location whose adéress is in I1+d, ADD A,LIYed) = Add the B-bit nuaber in the location whose adéress is in IY+d, 4s vou can sey we have a very versatile range of possible nuabers we can add to whatever musber is stored in the Accuatlator ~ any muster, any register, and virtually any way we care to define a wenory location. The one which is alssing i AD Ay (nn) “where we define the address in the course of the prograe, We can get aroun¢ this protles by writings= U0 Hon nd a, HU totes ageing the favoured rote of the HL register pair! We CAMOT specify the ataory location using the AE or BE repister pairs. he other Visitation implicit in all this is also the inherent Linitation of @-it nuabers which can only hold values up to 255, a8 we have already seen, For exanple, if we execute the instructionst- 4,804 AD A 81H Tmt ast a result of 1 in the Accumulator, but the carry flag will be set to indicate that the total of the two. nusbers exceeded 255, 80H + ann HOH = since 8 + 16 or 10H, ine frtra 1 of the JO1H having the eFFect of setting the carry flag. This would noraally go unnoticed, but for the fact that there is another instruction which also tates into account any setting of the carry flag’ icect= "ADU" or *eey Gk SseUee teres the overflow is recorded by the carry flag being set. Using this instruction, we can 248 nuabers qreater. then BS fogether with a chaining operation ive.:~ Supose we want to add SEBH (1000 Deciaal) to 7BOH (2000 Decieall,” then stone the result in the BC register pairs (0 AJEBH - Lover part of first nusber. ADD A,DOH - Lower part of second nusber. UDCA ~ Store result in C register. LD A,SH = Higher part of first nusber. AOC A,7H Higher part of second nusber. (DBA ~ Store resuit in B register, a Here, after the first addition of EOK and DOH, we will have the carry flag set because the result was greater than 255, Also, the Accunulator will contain BGH ~ check this for yourself. You sight expect the second addition of 3¢7 Deciaal) to Give 10 (ecinal) or AH. In fact, we get 11 {Decinal) or BH - because of the carry being set. Thus, the Final result is BBGH or 3000 Deciaal! We could repeat this process to consider any size of nuaber, and store the result in aesory rather than in a register pair. Bit Subtractior This is exactly the sane as G-bit addition, Aqain, tno sets of comands are available, one for ordinary subtraction, and one for subtraction with carry i.e, SUB s - Subtract 5. SBC 5 - Subtract s with carry. ‘Again, the notation *s* refers to the sane range of possible operands as for the add instruction. Another iaportant operation is: COMPAREN THO B-B17 NUMBERS When we “coapare® tno numbers, if they are the saae we say they are ‘equal*, Another way of expressing this is to say the difference between thea is zero e.g, compare & with 6 - they are equal, What if the second sueber is greater than the first? For exanple conpare 6 with 8? Here, on subtracting & - 8, we see the result of - 2 is negative, Sisilarly, compare 8 with 6. Here, the subtraction of @ - & = 2 i.e. the result is positive. We can see that the compare operation is essentially one of subtraction, We can thus devise a eachine code operation for “coapare', using the subtract instructions and the flags - especially the carry and zero flags. Suppose we wish to coapare a range of nuabers with the nuaber 5. e can use the instructions: LD -A,S = the nuaber we have (in the Accuautator). SUBN the ouaber being coapared, This gives the following resull If M= 5 (N equals 5) = The zero flag will be set (=1), carry flag reset (=0). IFN C5 (N less than S) ~The zero flag is reset; carry flag reset, 14H) 5 (MK greater than 5} - The zero (lag is reset} carry fag set. We can thus see that the test for equality is the zero flag, and the test for ‘greater thant will be the carry flag being set. Also, the test for "less than" is both flags being reset, The only probles with this aethod is that the contents of the Accumulator have been changed when using the SUB M instruction. Fortunately, this can be avoided using the "CP s* instruction, or ‘coapare with s*. NOTE: This compares the operand which can be a nuaber n, or another register etc, with the nuaber in the Accuaulator - the iaportant fact being that THE CONTENTS OF A ARE UNCHANGED HY THE OPERATION. The only effect is on the flags, Thus, for example, “CP S* aeans ‘*cospare the ‘aber in the Accuaulator with 5*, Also, *CP 8" ~ aeans "compare the contents of A with the contents of BY, and so on. Thus, reneaber that *compare® is exactly the sage as ‘subtract® with the iaportant difference that using ‘compare’ leaves the contents of the Accuaulator UNCHANGED, summepy. G-bit arithwetic using the 280 is Lisited t A01TION, SUBTRACTION, COMPARISON, Asay it can ONLY be perforaed using the ACCUMULATOR. Because of the nature of G-bit nusbers i.e, they can only hold values up to 253, we aust alnays consi any result with a value greater than 255, The CARRY flag is the iaportant flag which we can use to infore us of any overflow. Additional instructions i.e, adé with carry and subtract with carry, allow us to chain arithastical operations to deal with overflow, fF any overflow ive, ay KOBRAHSOFT Z80 MACHINE CODE COURSE” CHAPTER (5) LOGICAL OFERATORS, In this Chapter, we will look at the Logical Operator instructions available to the 180, There are THREE of these i. xo mR 19R The reason these operations are ieportant is that they operate on the individual bits of a single byte nuaber, Consider the first ~ the *AND* operation: BIT A BIT RESULT OF BIT A *AND* BIT B = we can see that the result of an *ANO* operation is to give us a 1 only if A AND B BOTH contained 1. Thus, in aachine code, if you "AND" (wo nuabers, the result is what you would get if you *ANDPed each of the individual bits of the two nusbers. You aay well ask, what is the point of such an operation? The answer is the "AND" operation is very useful in that it allows us to aask a byte so that it is altered to contain only Certain bits i.e. if, for example, we wanted to limit a particular nusber to lie in the range 0-7, we need to specify that OMY bits 0 - 2 contain inforaation - since if bit 3 contained inforsation, the nuaber would be at least ! Thus, we haves 00-0 6 Cr re These bits aust be 0 Thus, if we take a nusber whose value we do not know, and apply the "ANDY operation with 7, the result will be a nusber which Lies in the range 0 - 7, ¢ 105 T (the aast) 1 1 result of "MD" 000 © 0 0 1 4 Gnvange- 7. OTE:~ the 260 ONLY ALLOWS THE "AND" OPERATION TO TAKE PLACE IN THE ACCUMULATOR, The Accunulator can be "AND*ed with an B-bit nusber i.e, nj any of the other B-bit registers e. with (1198) or with (1¥+d), The instructions are shortened so the Accum B, Cy Dy etcy with (HL; tor need not be specifically sentioned i.e.t- AND 7 ~ aeans AND" the nunber in the Accuaulator with 7 AND E - seans "AND" the musber in the Accuaulator with the nusber in the € register. AND (HL) - nears "AND" the number in the Accumulator with the nuaber pointed to by (HL). = the Accuaulator is not aentioned in the instruction, The sane range of possibilities and the saae restriction to using the Accusulator also apply to the other two operations, OR" and “HOR, The “OR? operation is very similar in concept to the *AKD* operation i.e,:- BIA BIT 8 BIT AOR BIT B ° o ° ° 1 1 1 0 1 It 1 ' 2 It is obvious that the result of an *OR* operation is to give a1 if either A or B contained 1. ‘Again, you way ask, what is the point of such an operation? The “OR operation is very useful in that it allows us to set any bits in a nuaber i.e, sake thea Mf, for exaaple, we wished to ensure that a muaber was odd, then clearly we have to set bit 0. i LA, Muaber: oR sake nuaber odd, The above tuo Lines would be a typical asseably Listing, The concept of *X0R* - pronounced "exclusive or* - is also easy to understand, but its actual use in progras Liaites, ing is are The result of *10R* is a 1 only if one of A or B contains a I i.e, the result is the sane as for the *OR* operation in all ‘cases except when BOTH A AND B contain 1 i.e, HOR = OR ~ AND i.e.s- BITA BIB BIT A "108" BIT B ° 1 0 1 The last thing we aust consider is the effect these operations have on the {lags i.e.t- lero Flags- This fag will be on (=U) if the result is zero, Sign Flags- This flay will be on (1) if bit 7 of the result is set (et). Carry Flags This flag will be off (20) after *AO", °OR*, and CIDR, i.e, carry is reset. Parity Flags This flag will be on (1) if there is an even ausber of bits in the result i.e.t- orto 444 ff er Malf-Carry Flage This flag will be off (0) after "ANDY, “ORY and “10R*, Subtract Flagi- This flag will be off (0) after “ANS, “ORY and "10R. Use of Logical Operations on the Flagst~ There is a special case for these Logical Operations = where the Accuaulator operates on itself 4. MDA - Ais unchanged, carry flag is cleared, RA = Ais unchanged, carry flag is cleared. HORA = Nis set to 0, carry flag is cleared, These instructions are often popular because they require only ONE byte to do what wight otherwise require two, such as LD Ayo. The carry flag often needs to be cleared, e.g. as a aatter of routine before using any of the aritheetic operations such ase AOC ~ Add with carry, SOC ~ Subtract with carry, ~ this is easily done by using the instruction AND A, without affecting the contents of any of the registers. o SUNHARY OF THE EFFECTS OF LOBICAL OPERATORS ON THE FLAGS. Wresonic Bytes ine Taken Effect on Flags " sno fepiter 1 ‘ ol ho mater 2 1 or rye d wo ot) \ H or rred 0 108) 3 " ob arod avo ave 3 " or riod me resister ‘ en) 08 Hanber 2 7 ores on aw) \ 1 or roe om tise) 3 8 of OR (IVA) 3 9 or ee OO roe Renister ‘ en) YOR water 2 : oririres vor ty 1 1 ee) ron (118) 5 " or tro. ror tavea 5 " or rio. The notation used ist X= acans flag is altered by the operation, 0 = means flag is set to 0. 1 - means flag is set to 1. ~ = weans flag is unaffected. USING 16-BIT MUMBERS, So Yar, we have only aainly dealt with single byte (B-bitl munbers. ke know that the register pairs ive, HL, DE, BC are capable of holding 16-bit nunbers which can go to 48535, The inportant point to reaeaber is that instructions using 14-bit nusbers will always be auch slower than B-bit - this is because the instructions using 14-bit nusbers contain 3 or sore bytes which have to be fetched fron sesory. ‘The addressing wodes available using 16-bit musbers are:~ Innediate Exten ‘An exzaple of this is the instruction: U0 reynn This is the equivalent of G-bit lasediate Addressing, It is serely Inediate Addressing extended so as to accosodate 16-bit data transfer, w As stated earlier, instructions that operate on Ib-bit nuabers are longer and slower than those for O-bits. The forgat for fanediate Extended Addressing is thus: Byte | Instruction Byte 2 nl - 1.0.8 of the auaber. Byte 3 m2 ~ 4.0.8 of the nuaber, Me use this type of addressing instruction to define the contents of a register pair, for exaaple a pointer to a sesocy location, Register Addressing You aay recall that Register Addressing is the mane we give to an instruction if the value we aant to aanipulate is stored in cae of the registers. The sane holds true for Jé-bit instructions, except that there are only a few instructions of this type in the CPU's repertoire, These are aainly relating to arithaetical operations, and are very liaited in the register combinations alloxed, 0 HL 8 We will aention again the preference the CPU has for its HL register pair. Sowe instructions can ONLY be carried out by this register pair. This is especially true of arithuetical operations, as we shall see later. Register Indirect Addressing, This is the nase we give to instructions where the value we want is in aewory, and the address of the seaory location is held by a register pair e.g.:- JP (HL). Extended Addressing, This is sisilar to Register Indirect Addressing, but the value you want is not in a register pair, but in a pair of sesory locations e.g.2- LD HL, (nn) ~ where an aust be specified at the progras stage. Exaapies, 1), Tanediate Extended Addressing: Try this sual aachine code progran: Deciaal Nos. Her os. Hnesonies Comments 1, 15, 0 01,08 00 LD 6c,FH oad BC with FH (15 Decial), En) 9 rer Return to Basic. POVE the nuabers in to a suitable location e.g. 32000 ~ 32003, RUN the progran withs~ PRINT USR 52000 (ENTER). The result: is 15 i.e, the nunber in the BC register pair. (2), Register Addressing: 330,64 21,00,40 LD HL,4000H Load HL with 4000H (16386 Deciaal), 1,15, 10°00 (0 BCFA Load 8C with FH (15 Deciaall, 4 0 ‘00 HC Add the two nuabers 20 a rer Return to Basic, POKE the nunbers in, and RUN with PRINT USR 52000. The result is 15! Why not 16386 +157 Me did adé the two nuabers, but the result is stored in the HL register pair! To see the correct total, considers- (2), Extended Addressing 35,064 21,00,40 LD HL,A000H Load HL with 4000H (16384 Decinal). 1415,0 1,0, 00 Lp BF Load BC with FH (15 Deciaal?, 9 w AOD LBC ‘Add the two. 34,100,125 22,64,70 LO (70604) 8. Put HL value in 32100 and 32101. 237,75,100,125ED,48,64,7D LD BC, 7D6AH) Get value of BC fron 32100 and 32101. 201 a fer Return to Basic OME the nuabers in, and RUN with PRINT USR 32000. The correct result is 400FH (16399 Deciaal), A better way would be to use the PUSH and POP instructions, but this illustrates another way which should be clearer. w SKOBRANSOFT ZB0 MACHINE CODE COURSE" CHAPTER (4) KOBRANSOFT KD1_ DISASSEMBLER INSTRUCTIONS FOR USE Introduction, In this aonth's newsletter we have enclosed a copy of our *KSFT KDI DISASSEMBLER* (which, incidentally, ve used to sell separately for £5.951). KDI is an efficient and easy-to-use disasseabler for your Spectrus. It can be used to list @ Gisassendly of the 180 anevonies of any progr any either to your T.V. screen, or to a I Printer, Tt also allows easy Interchange to and frou Basic, and also contains a Muaber Converter to convert (a) Hexadeclaal to Decieal susbers, (b) Decisal to Meradeciaal pushers, Also, it contains the facility to Inspect and/or aodify any section of seuory ~ allowing you to easily enter sachine code as a series of Hex nunbers. Lownie, For the 40K Specteun, type typer= LOAD ** CODE (ENIER) as tor the (OK Spectre vusing~ LOAD ** CODE (ENTER). The progran will then run, displaying the arssage:~ "To Startt Press BREAK*, On pressing the BREAK Key, XDI goes into the Connand Mode - with a flashing cursor at the botton of the screen, At this stage, the following coneands are available:~ LOAD ** COME CENTER. For the 120K Spectrum, select 126K Basic fron the Tape Loader Menu, then KOL will also run on the 120K Spectrua in 40K Kode, again being leaded Conands, (1, Huber Converter. (ND, To access the Muaber Converter, press “W". The vessage:~ HEE or DEC? is displayed, To convert a Hex toa Decival nuer, press 'H*, Wor, enter your Hex Hueber. NOTE:~ Any leading zeros MUST be included i.e, enter 3B Hen as 0038, etc. Any noraal ex letters tA = FY say also be entered, On pressing ENTER, the result Is shown, To convert Decieal to Hex, press "K", then *D* for Deciaal. Now, enter your Decisal nuaber WITHOUT leading eros. Tressing ENTER gives the result. 12), Inspection of Nenory, and/or Insertion of lex Nusbers. (1). By pressing I", you have two functions available: (a) Inspection of wenory ~ ater pressing "I", the Letter M* appears. If you now enter a four digit Hex nusber (again Including Yeading zeros), on typing the fourth digit, the address is shown, together with a two digit nuaber to its right. This 1s the content of that aesory location. On pressing ENTER again, the next location Is shovn in a sisilar way. Thus, by Contineally pressing ENTER, a range of locations can be studied. To go back to the Cossand Mode, press °K". {) Insertion of Hex nusbers in acaory - after pressing "I", and typing in your wesory location, you can change its contents by typing in a 2 digit Hex nuaber ‘again using leading zeros). For exakple, suppose you press ‘I*, then type 7000 to see the contents of location 7000 Hex, Suppose this shows 00, If you now type, say; F3} Uhis nvaber is shown and is inserted in that. location - check by going back to Conaand Hede (press *K"), press *I*, then 7000, folloved by ENTER - you will see F3 at 7000! This Is a convenient way to enter a aachine code progran as Hex muabers. Again to return to Consand Mode, press (0), Disassesbler. (0), HOTEL Any section of wesory say be disascenbled ENCEPT that occupied by KDI, Any atteapt to disasseable this area will broduce the aessager~ "INVALID ADDRESS". To enter the disassesbler ode, press "D*. Next, type (in 4 Hex digits) your required start address, Yeu can new also sinilarly spectty a 4 Hex digit end address, If you don’t, the only difference is that KOI WiMT continue its dlsassenbly up to 65535 (TFITH), which is probably inconvenient, especially when outputting to your printer! In the case of no specified end adéress - press ENIER. You are then asked if you require @ printout to the 21 Printer, If yes ~ press "J", Hf no = press *H, when the Tisting will appear on the screen, To list wore ~ press ENTER, To end the listing - press "F', When an end address Is specified - ENTER is not needed ~ the enquiry PRINI? appears on pressing the last digits NOTE: To get 7%, press Syabol Shift and "V" Keys. If you do nat speclty an end address, you can stop a continual printout to 21K Printer by pressing *PREAK*, This will return you to Baste, with the usual error aessage. a (8), Return to Basic. (7), For a NORHAL return to Basic, press *R* while in Coneand Mode ~ you will be returned to Basic. To re-enter KDI fron Basic, ‘ypei~ RANDOMISE USR 59625 (RUN USR 57625 on the 126K Spectrual, then press “GREAK®, This will take you back into the Conaand tote, As you have seen, KOL 1s an easy-to-use, but quite powerful disasseabler. We suggest you try it on any sources of aachine code you can get hold of. As an exercise, why not try disasseabling your Spectrua's ROM? This Is easily done by using a start. address of 0, oF 0000! Also, check any Basic Loaders in any of your gaees ~ if on Listing they contain a REN which gives a lot of unusual characters ~ it Is likely to contain aachine code. Try disasseabling the area around the start of Basic i.e. SCCBM (or SDOSH. You could also try entering the *Screen Nover* routine ne showed earlier which uses the block aove consand LOIR, w "KALI EDITOR/ASSEMBLER raronucrt HAL is a aulti-purpose Editor/Assesbler program which allows you to enter and edit the source code (anesonics and label naees), produce the object code (the Hex aachine code), and create hard copy on the ZU Printer, or cassette copies on tape. It operates in two distinct parts. Firstly the EDITOR allows entry of the Source Code by seans of Line nusbers in a sisilar Fashion to a Basie program, and allows efiting of that source code, In the second part of the operation, the Source Cade is asseabled into the actual Hex code (chinct coded. LOADING KAL. For the 48K Spectrur:~ Type LOAD ** and FLAY in the progran, For the 128K Spectrus:~ Select (0K Basic, and proceed as for 48K Spectrua, THE EDITOR. ving Toaded FAL, the progran will ask whether you wish to use NEW TEXT or to CONTINUE with existing tent. As at the start there wilt be no text (isting) Hn the text bri fer, press "HY in response to the proapt. (See later for the CONTIRUE option), The aensage vill éisappear, and the curser vill appear in the lover lett corner of the screen. KAI is now ready to use, USING THE KEYBOARD IN KAL, As the muster of conpands accessible fron HAL is auch saaller than the nusber fron Basic, the keyboard operates in a Sioplified nanner, EXTENDED aode is not available, mor is the GRAPHICS node, or CAPS LOCK ode. KAL knows when lover case letters vay be needed, ‘and displays capitals at all other tines. Wherever possible the KAL consands are accessed by the 5 heys as the equivalent teywords in asic. These comsand nanes are shown below, and are only available when the cursor fs at the Left hand side of the bottce line: USTI~ on Key K. FDITE~ on Key 1 with Caps Shift. SAVES on Key 5. LOAD:~ on Key J. on Key A on Key 1. on Key Ye Other HAL commands that have no Fasic equivatent or are mat Basie keywords are as follows, and are also only accessible with the cursor at the Left end of the Hin RENUK:~ use Key Ne VERIFY:= use Key Ve AUTO:~ use Key D, ASSEMRLES~ use Key Rs Cursor control functions are accessible wherever the cursor is positioned, and ar = on Key 5 with Caps Shift. on Key 8 with Caps Shift, DLLEIE on Key 0 with Caps Shift, ENTER on Key ENTER, AIL other alpha-nuveric heys operate as novaily giving the appropriate letter or nunber. Use of the Syabol Shift with a Hey SHIT give the red syabol shown on that key top, providing it is a single character syabol i.e. *!* is available foe fey | lus Syabol Shift but using Key "0" plus Syrbol Shift will produce no result since *OR* is not a single character syabol, Syabols neraally accessed by the use of tin Extended Hode in Basic are not accessible frow KAL. The only tise you will need to se CAPE SHIFT Lo access a capital letter Ig when you are entering aa Line tm KAL. AU ALI other tees, KAT autonatically displays capital letters. {THe SCREEN DISTLAY. The screen display of KAI is divided into fields. This produces an ordered fore of listing that is very easily readable, a The cursor control functions autoaatically recognise the boundaries between the fields, saking entry of a Hine into the tent butter a siaple operation, ENTERING & LINE, Only ONE instruction per line is allowed, and the line aust contain a tine avaber between O and 9999. The progran Line say hen next contain a LABEL to Identify the instruction In this line, The 4 fields Line Ho, - Ist 4 characters + 1 space. Label Hane = ext 5 characters + 1 space, Operation Nase - Next 4 characters #1 space. Operands ~ Rest of line, With the cursor to the leit, type a line nuaber e.g. 10, Press SPACE, this advances the cursor to the Label field. For a0 label press SPACE again to go to the Op Mane field, AIL prograns MUST start with an ORIGIN address, defined by OR6, Type O85, press SPACE to aove to the Operand Field. Type 7O00H to specify 32000 Decisal. Press ENTER and the line is coaplete. Using the 4 Fields into which each Line is divided, always enter a Line nuabers then a label if needed (aax, 5 chars); enter the Op Kase CALL, LD etc); enter the operand into the last field, With 2 operands, they aust be separated by a comma, e. 10 op 7H00 0070 (> Ay20 0030 exo NOTE: Each progran MUST have an END instruction, EDITOR comnanas aust. ress the k hey, then ENTER. For sore Listing, press SPACE. Press "K* then a line muaber then ERTER lists froa that Line, To list to a 21 Printer, press °X", then / (Syabol Shift and Key °V*) - ENTER Lists to the printer. ft Press Fey ‘0° ~ gives AUIO. Type a Jine nusber then ENTER, The Line nuabers will be autonatically displayed and increase by 10 each tine you enter a line, wm. Press Caps Shift and Key 1 - gives EDIT. Adding a line nusber edits that line, Edit as for Basic. Nee Press the ‘A’ Key and ENTER, This clears all the text fron the text buffer. ReIUsy, Press 71 then ENTER ~ returns you to Basic. To return to KAly type R.USR 58926 ENTER. 8). ROWUN, Press “H* - gives RENUK, Now, type the new interval between lines (J to 99). Press ENTER and the prograa is renuutered, THE ASSEMBLER, The assenbler part of KAL converts the mveaonics into Hex code, The anewonics in the Listing are called the Source Code, the asseabled Hex code is the Object Code. reruns, x FAL will accept Oeciaal or Hex nuabers, and defaults to Deciaal, Nuabers HUST start with a nuneric digit i.e. 0 to 9) and Hex nusbers sust have a suffix H. LV a tox muster starts with a letter (A to Fl, it aust be preceded by a zero i.e, DOO) Her ust be written 00000K, and FF Hex as OFF. 2/0. Such juaps as these aust be within the range +127 to -128, a Lanes, Any label can be used, to a aacimue length of 5 characters, ASSEMBLER DIRECTIVES. is specifies the start address in seecry where the code will reload with LOAD**CODE, O86 aust be the first line you enter This specifies the end of the progran and MIST be included. jes a single byte at the current address, Must be in the range 0-255, vet. Defines the next two bytes at the current address in the range 0 ~ 63535. CCOMANDS, ASSENBLE, So Press *R* ~ gives ASSEMBLE, 3 choices are available:~ (1), Press *R* then ENTER. This gives an asseably with no display and is the fastest. (2), Press "Rr then Syabo! Shift and -V" Igives /), Pressing ENTER gives an asseebly to the II Printer. (3), Press "RY then *S* then ENTER - gives an assembly to the screen in full detail. PAUSE with "I" then ENTER, This clears the text butter. CONTINUE, Pressing "C* in response to ‘Mew Text or Continue?* does not alter the text when returning from Basic. °N’ clears it. CASSETTE ROUTINES, SWE. You can save either the Text or Object buffer to tape by pressing ia 1), TEXT BUFFER:~ The fora is SAVEtnase* T, Saves the text to tape. (2), OBJECT BUFFER: The form is SAVETnane"C. Saves the object buffer as bytes to tape. vey. Press 'V". The fora is VERIFY*naue*, There is no need to specify text or code. Lown, The KAL will ONLY load TEXT files. 2 options are availables~ (11, Press ‘J". The fora is LOAD*nane’N, The *N* aeans NEW - the existing text buffer is cleared, as is the label table, need not be specified. (2), Again press "J", The fore is LOAD'nane'C, Here "C* tmeans CLEAR - the text buffer is cleared, but the label table is protected, We hope you enjoy using your KAL asseabler, and find it useful in writing aachine code routines. TKOBRANSOFT Z80 MACHINE CODE COUR CHAPTER (7) USING 16-BIT NUMBERS, We will nox discuss the use of 16-bit (2 byte) nusbers in aachine code, As we fiscussed earlier, the largest nusber that can be represented using @ bits is 255. Clearly, this would be a serious Moaitation, particularly if we wanted to specify an address in the region 256 to 65535. Thankfully there is a way around this robles in the 189 chip, using 18-bit (2 byte) nushers to represent addresses in the range 256 to 65535. SPECIFYING ADDRESSES USING 16-BIT NUFOTRS, PLEASE WOTE:~ AIT addresses MIST be specified by a 16-bit nuaber, even if it is in the range 0 to 255. This is because the CFU Is set up to recognise that a nusher is not to be taken as an adéress unless it Is specified by 2 bytes of 8 bits each, It ccan be regarded as a convention, if you lil You aay reaeaber that this was iaplind hy the use of the instruction’ WA, ton) You aust also reseeber that 16-017 MUMPEFS ARE STORED IN REGISTER PAIRS HIGH KUNBER FIRST, LOW NURRER SECOND, In coaplete contrast to this is the convention ofs- SHORING 16-B11_NUNRERS IN MEMORY, Here, the convention used is COMTLETELY OFPOSITE TO TWAT ABOVE, 1.e, WEN LOADING 16-B1T NUMBERS INTO MEMORY, THE LOW BYTE US ALWAYS STORED FIRST IN HENDRY! Consider the exagple of placing the contents of the ML register pair into eesory, Suppose that the HL register pair Contains the nueber 7D00H or 32000 Decimal. As we have stated, in the registers, H contains the HIGH byte, L the LOW byte. (Sinilarty, for RC, B contains the HIGH byte, C the LOW bytey also for DE and AF). Thus we can show this as:- wou 7 00 Hex). This result would be achieved, for exasple, hy executing the instruct WL, 700H Now suppose we wish to place this nusber in nenory at, say, address GOOCH or J276B Deciaal. This can be done using the instruction:~ U0 UAddress), HL. where (Address) is (B000H), Resenber, the bractets mean "the Location pointed to'. On executing this instruction, find would Nenory Location Contents 32768 wn9 ses LOW byte FIRST, HIGH byte SECOND! Again, this 4s siaply a convention which seans it is the way the 200 has been Progranned, but it is MOST IMPORTANT that you reaember it, Again it is t= 1M REGISTERS:~ HIGH byte FIRST. 1H MEMORY. AND PROGRANS:~ LOW byte FIRST. Thus, please renesber when using 16 hit nushers, ALWAYS CONSIDER CAREFULLY THE ORDER OF THE BYTES. We vitt use the above as an exasple, The whole progran isi~ a 0 i, 7008 to ca00H RET Renenter, don't forget the FET instruction - this is to ensure we return to Basic! The aachine code instructions arei~ Mrenonics, Instructions Ulex. Hos.) Deciaal Kos. LHL 7Do0H 24,00,70 35,00,125 Lo ceo00H HL 22,00,60 et oy NOTE: This ts the way the progran instructions aust be stored in aeuory. The progran can be entered into aesoryt~ (11, By POKING in the values to a suitable location using a Basle progran such asi~ ‘0: FOR A=30000 TO $0006: INPUT B:POKE A,BrNEXT A (2), Use the KDI Disasseabler we supplied in the Last newsletter, Use the "I" facility to tnsert the Hex, au address 7530H ($0000 Declaal). S starting at Maving entered the progran into aeuory, run it by typing RANDOMIZE USR 30000 for RUN USR 30000 on the 128K Spectrua), NOIE:~ The 126k Spectrun souetines won't accept the RANDONIZE USR cossand, Exanine the vencry locations at #000H and B001H (32768 and 32749) using FRIMT PEEK 32748, then PRINT PEEK 32069. You will Hinds 3276820} 32769125 (if you have done it correctly! We apologise for going into so auch detail, but this is a difficult concept which MUST be well understood to avoid aistates. OVWER 16-B11 LOAD INSTRUCTIONS, ‘As well as using the register pairs, we can also load 16-bit nuabers into the Index Registers I and 1Y usingt= WM, nn way, mn We can also interchange nuabers to and frou neaory and register palrs usingt- {0 Con rr Lb ton), 1 LD Gon), IY where nn Is a 16-bit musber, rr ts a register pair, We can also haver~ Wer, (and LOM, ton) LD 1Y, (on = the reciprocal of the above instructions, exercise Check your understanding of the previous exayples by finding the contents of the Systen Variable PROG, which is a two byte rusher stored at address 23635 (SCSIH). This will be either 25795 (SCCBH), or 23813 (SDUSH), depending on whether a sicrodrive Is Fitted or not. e can do this frow Basic using:~ PRINT PEEK 23655 6 Z560PEEK 23636 o 11 now do the sate thing using the following sachine code program:~ Hneaonies Machine Code Instructions (ex and Dec Nos.) U0 BC, (5053) €0,48,58,50 237, 75,83,92 RET a 201 Again enter the nushers into aenory as before, and execute the pragran by typing PRINT USR 30000, The nusber 29755 or 23813 should appear on your screen. The reason for this 1s that when a FRINT USE coanand is used, on returning to Basic, the nusber in the BC register pair Av printed. In this case It 1s cur answer = the address contained In the Systen Variable PROB, NOTE:~ The LD RC, ton} instruction is a FOUR BYTE instruction! Tar aethod to the above Lo deteraine the values of the addresses stored In other Systen Variables (see list on Ps 173 of your Spectrue Aanual. Reatmher ~ soar are only one byte ouabers! Check your answers using the FRINT PEEK eethod. Also, PORE a few values into different araory Locations and see if you get the correct results using the above aethots, LO-BIT ARITHMETIC In Uhis we again have a favoured register pair ~ the Hl register pair. Hovever, we do not have such a aide range of options as in B-bit aritheetic! N6-BIT ADDITION, The possible operations are:~ 00 LB A HL DE AD HL HL 00 LSP These are the only optiens! Note that we cannot add an absolute ousber to HL e.g. ‘ADD HLynn® is not peraitted, We can get around this using: (0 6 ,n0 400 HL DE Nevever, this uses up four B-bit registers - not very elegant! Also, there is no addition between HL and IX and IY. Niether {s there any LOAD instruction which allows you to transfer the contents of the Index Registers to BC or DE, so we aust PUSH 11 PoP De AD WL DE ise, the contents of IX are fUsied onto the stack, and POPped off into the DE register pair. This is then added to HL with the Last instruction, EFFECT OW THE FLAGS, The sain flag affected is the Carry (lag. (Ihe subtract flag is also affected, but its use is very lisited). The carry flag NiMH be set UF there fs any overttow Tron the high bit of the H register ~ any overflow frou the L register autoeatically goes into the W register in any 16-bit calculation. He can also have "ADD WITH CARRY" or *ADC*, which operates in a sixilar nanner to TADDY In B-bit aritheetic, with the sane register pairs i.e, t= ADC HBC ADC ML OE ABC LH 0 HL SP w 16-817 SUBTRACTION, Hote that you cannot have subtraction without carry. Thus, you aust always check the status of the carry (lag before any Ub-bit subtraction operation. It is usually best to include an instruction to clear the carry flag first eg. an "AMD AY instruction will do this without altering the contents of the Accumulator (see Logical Operators earlier). The allowed instructions are: SBC HL, BC 8G HL,OE SOC HL HL SC HL SP EXERCISE Using the Systes Variable SIKEND (start of free aesory space), write a siaple progran to calculate the value for the anount of free space. (int:~ Load iL with the value in SIKEND, then subtract SP = the NEGATIVE result will be the aaount of free spacel. See later for the solution, FFECT OF DWINE Three other flags are alfected by the *HOC* and *S8C* instructions which were not affected by the siaple ‘ADDY Instructions. These are the ZERO, SIGN and OVERFLOW flags. Each Is set according to the result of the operation. NOTE: The Index Fegisters are liaited to OMLY ADDITION WIIMOUT CARRY! Also, the range of registers which can be added to then is very Linited i, aon 11,8 00 1Y,86 AnD 11,0 0 1Y,0E 00 11,1 400 1Y41Y 200 11,5? a0 1,8 contents of the Systen Variable SIKEND {.e. t= LO HL, (SIKENDD. NOTE: The value of STKEAD 1s SC6SH (25655 Deciaall, How we aust subtract SP using SEC ML,SP. However, REMEMBER we aust clear the carry flag first using AND At However, because the Stack Fointer 1s (usually! higher in weaory than the top of your progran, the result will be negativi To convert this to 2 positive value, we can use the BC register pair (we could also use OE). Firstly, we aust shift HL to 8C ~ but tere is no appropriate LOAD instruction, but we can get around this using the stack by using a PUSH then a POP thust- PUSH HL Por aC = this beeps HL the sane, but transfers its contents to BC, To get HL = -BC i.e. the negative value of BC, we aust subtract BC frou HL TWICE. Reseaber, though, that the carry fag has just been set by the SC HL,SP (since SP Is greater than HL), $0 we aust clear it again using ‘AND AY, IiL now contains the negative value of its previous contents or the positive nuaber of bytes left.To get HL back into BC ito get a result from the USR function) we can PUSH HL, POP 8C, and return with KET I.e,t= LL, (STKENDY xD A SUC HLS? PUSH HL For ec ao a SBC Ht nc SRC LBC Fusi or ac Per ay KOBRAHSOFT 280 MACHINE CODE couRSE~ CHAPTER (8) USING JUNPS AND LOOPS IN HACHINE CODE. ‘4 juap in aachine code is the Fasic equivalent of the "GOTO" instruction, i.e. the progran juaps to the Line in Basic, or the specified address in aachine code. this is a very power‘ul instruction, but you MUST ensure that there is a seaningful hachine code instruction at the juap address, otherwise unpredictable results will follow! There are THO types of *ivap" instruction available in aachine code} these aret~ (00, The ABSOLUTE junp. (2), The RELATIVE or JUMP RELATIVE np. The ABSOLUTE juap can be sunsarised as:~ we where the IP is the JAP instruction, and xx ax is a two-byte (16 bitl musber. Since the whole of the Spectruneewory can be addressed by a 14 bit nuaber, the ARSOLUTE juup allows us to juap to ARY position in the Spectrun’s aesory! The Jjuap can also be dependent on the status of one of the flags, e.g. the carry Flag, Me can this haves BP ey nn ort 3 1, 0000 This would read as *iuap if zero to address rerot. This is the address the Spectrua juaps to when you switch on - the onputer is said to RESET. Ue can itlustrate this with the following siaple sachine code progran, Type POKE 32000,195; FOKE 32001,0; POKE 32002,0. This puts the J bytes 195,0,0 at 32000. This is the siaple instruction JP 0000, or RESET, Activate by typing RANDOMISE USR 32000 (ENTER) - the computer RESETS! AIL you have told it to do is to juap to address zero and start eatcuting the instructions frow there, which is what occurs when you switch on. The other ABSOLUTE JUNP instructions can be suamarised as:~ INsTRUCTION NEROMICS Hex N05, DECIMAL NOS. JUN TO ADDRESS SPECIFIED BY (HL), hm “a os JUMP TO ADDRESS SPECIFIED BY (11), Pan mo es 2 23 {JUMP TO ADDRESS SPECIFIED BY (IY), aay ne 253 25 JUMP TO ADRRESS SPECIFIED BY xx x1, PADDR C3 ax ax 195 oon JUN, TF CARRY TO ADDRESS x xx, JP C,AtDR DA ax nx 218 a x JUMP, IF MINUS TO ADDRESS xx xx, JP H,ADDR Fea ax 150 1 JUMP, NO CARRY TO ADDRESS xx xx, JP NC ADDR D2 ax nx 210 ax ax JUMP, NOT TERO TO ADDRESS xx xx, JP NL, ADDR wm 1 no JUN, POSETIVE TO ADDRESS xx xx, JP PY ADDR Flax 22 ax oe JUSP PARITY EVEN TO ADORESS ax xx, JP PE, ADDR EA ax ax 24 ax we UMP PARITY ODD 10 ADDRESS ax xx, JP PO,ADDR ED an ax 2b ax ax JUNP TF TERO TO ADDRESS ax xx, JP 1, ADDR Chae ax 202 ax ae a This is a convenient point to digress slightly to consider how the 28 CPU in the Spectrua handles aachine code ansteuctions. The 280 contains a 16 bit register called the PROGRAK COUNTER (see earlier), which is used to store the adrress OF THE NEXT INSTRUCTION 70 BE EXECUTED. Thus, if the CPU encounters a2 byte instruction, it adds 2 to the program counter (usually abbreviated to PC); with a3 byte instruction it adds 3, and so on, However, with a noraal JUNP instruction, on encountering the OP CODE C3 (Hex), the CPU knows that the following 2 bytes fore a 16 bit address which specifies to where it faust juap. As usual, the first byte after the C3 is the LOW order byte, the second is the HIGH order byte, How does the CU “know it needs to get the jusp address froe the next 2 bytes? - it is progranaed to do just that, Reaeaber, the OP CODE is the first byte of an instruction which specifies its type i.e. a JUNP, or an ADD etc. Returning to the absolute juap i.e, JP xx xx, it can be seen that there are two aain disadvantages with this instruction ~ these are: (12, Me do not always need such a "Long? juap - but it still needs 3 bytes to execute. (21, The progran cannot be easily relocated to a different area of aesory, since we are specifying an ABSOLUTE address i.e, fone which will coly give the correct result in one area of weaory. Fortunately, there is an alternative instruction in the 180 ~ if the JP xx ax or ABSOLUTE JUMP is considered as a “LONG juap, the alternative *IUMP RELATIVE? instruction or JR d is the ‘short juap', The *d* is the relative displacenent frou the current address, and since it 1s only specified by one byte, we can ONLY have JUKP RELATIVE iuaps of 128 (i.e, juaping backwards), to #127 (i.e, juaping forward), ‘he general fora of the instruction is := wkd + where 4 is the displacesent fro the current position. The aain advantage is obvious ~ the distance juaped is specified in only ONE byte and the whole instruction only tates 2 bytes, The value of the displacenent *d* is added to the PC, thus the PC is always pointing to the next instruction specified by the juap relative. Sinilarly for a case where a condition is to be aet i.e. IR ccd e.g. IR Tyd. To illustrate this sore clearly, consider the progran: ewory Location Moesonic 32000 1 BYTE) 32001 QR 1, 2 (2 BYTES! 32003 L0 B0 (2 Bytes) 32005 Nexts-——LD HL, 4000H (3 BYTES) 4 the JR instruction at 32001 is ignored by the CPU i.e. the zero flag is not set), the CPU executes thus:~ (1), Load the single byte instruction at 32000, Since only 1 byte, set the PC to 32001, (2), Execute the instruction i.e. add contents of B register to A register. (3). Load byte specified by PC at 32001 - byte is part of a 2 byte instruction, so add 2 to PC to eake it 32003. (4), Get next byte to conplete the instruction and execute the instruction - the result here is to ignore the jus era flag is not set. (5), Load byte specified by the PC at 32003, Byte is part of a 2 byte instruction, so add 2 to PC which is now 32005, (6), Get next byte to coaplete the instruction and execute the insteuction i.e, load the @ register with zero, since the NOTE: At location 32001 the prograw encounters the Relative Juap instruction, since the zero Flag is not set in the above ple, the juap is ignored and the next instruction is executed i.e. LD However, if the zero flag WAS set, the CPU would ADD THO (the anount of the displacesent for the juap) to the PC, which would now aake it 32005 i.e, the next instruction to be executed would be the LD HL,4000H at 32005 - under these conditions the LD 6,0 instruction would be OMITTED or juaped past. Thus, if the zero flag is SET, the LD 8,0 is juaped over. NOTE: We can also have a NEGATIVE JUMP RELATIVE, AS an exercise, consider what would the effect be on the above prograa of substituting 4 JR Z,-2 instruction for the JR 2,2? For the answer, see the bottoa of page 4! (Hints~ Reaeaber, the PC will be pointing to 32003 again, since the JR Z,-2 is still a 2 byte instruction). Also, can you see how the displacement ¢ would be represented as -2, a NEGATIVE nuaber? a We can have a range of jusp relative instructions for various fap conditions also, as for the absolute juaps, Hovever, he range available is here lisited to the fol Instruction, JUMP RELATIVE, displacetent. JUAP RELATIVE IF CARRY, displacenent, SUMP RELATIVE NO CARRY, displacenent,, JUMP RELATIVE IF 2ERO, displacenent. JUMP RELATIVE MOT ZERO, displacesent. Using *For..-Next* Loops in Nachine Code, owing: ~ Hnesonic Hes Noss Decimal Nos. Rd 1B xx aw Rod Ban 5b nx RNC, @ 30m (Bs Rid wu on IRN, 6 20 3 You are probably faniliar with the usual fora of a *For...Next* loop in Basic, ies: Jor FORT = 1106 LETC C+ 30: NEAT T A sinilar case exists in aachine code, but in a slightly different fore. We could do this in aachine code thust- Lonr wat way Wet We 8 re JR NI, LOOP 5 Set counter to 1. j Maximus of counter + 1, pletc=cey, j Incresent counter. sis B= A? 514 not Loop again, This would work, but it is a very bad piece of progransing, since we are tying up 2 register pairs - one to increase, and ‘one to hold the eaxiaua; and the instruction which incresents the counter does nat set any flags on coapletion. A auch better ‘ay would be to use a countdown! He know we have to do the Loop & tines, so why not set the B register to 6 and count. dovn? This gives ust Lor As you can see, this is far aore efficient, NOTE:~ The 280 CPU has a special instruction which combines the last two (0 Bb wee DEC B JR NL, LOOP 4 Set counter. sletC= Cel, Decrease counter. + Loop if not finished. 5 above i.es3- DM 4 This stands for “decrement the B REGISTER, and juap if not zero*. The J is the relative displacesent as in the JR instruction. Tt is a THO BYIE instruction, which saves one byte on the shove coding, Because of the existence of this special instruction, the B register is usvally used as a counting register. The obvious Liaitation of the *DINZ” instruction is that it can only count up to 256, However, DIN instructions can be nested in a siailar way as for the Basic For. Next Loopst BrsLOOP UTvo0r LB, 104 5B = 16 Deciaal. PusH aC j Save value of B register on Stack, Lv 8,0 j Set B= 256 1 My required calculation ete, DINE LITLOOP 5 Done 256 tives? POP at 1 Bet back value of 8, DINE BIGLODP Do bigloop 16 tines.

You might also like