Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
1K views

Machine Code For Beginners

Machine code is the code in which the computer does all its work. A machine code program, though, is much more difficult to write and less easy to understand than a program in BASIC.

Uploaded by

amiga68000
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
1K views

Machine Code For Beginners

Machine code is the code in which the computer does all its work. A machine code program, though, is much more difficult to write and less easy to understand than a program in BASIC.

Uploaded by

amiga68000
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50
INTRODUCTION TO MACHINE CODE BEGINNERS USBORNE INTRODUCTION TO MiRIGhIINe CODE FOR BEGINNERS Lisa Watts and Mike Wharton Illustrated by Naomi Reed and Graham Round Designed by Graham Round and Lynne Norman 6502 consultants: A. P. Stephenson and Chris Oxlade ROCKFORD PUBLIC LIBRARY Contents What is machine code? Getting to know your computer The computer’s memory Hex numbers Peeking and poking Inside the CPU Giving the CPU instructions Translating a program into hex Finding free RAM Loading and running a program Adding bytes from memory Working with big numbers The carry flag Big number programs Displaying a message on the screen Jumping and branching Screen flash program Going further Decimal/hex conversion charts Z80 mnemonics and hex codes 6502 mnemonics and hex codes Machine code words Index First published 19% Usborne Publishing Ltd, 20 Garrick Street, London WC2E SBI, Exgland. 1565 Usb o ication may be reproduced, stored in a retrieval system or tansmitted in any form or by any mean: Schanical, photocopying, tecoreing or otherwise, without the prict permission of the pul ‘The name Usborne a 2 Printed in Spain by ‘Trade Marks of Usborne Pub ralica, S. A. - Depésito Legal hing Lad 33.785/1983 About this book This book isa simple, step-by-step guide to learning to programin machine code. Machine code isthe code in which the computer does all its work and programs written in machine code run much faster and take up less memory space than programs in BASIC. A machine code program, though, is much more difficult to write and less easy to understand thana program in BASIC, This hook takes you in very easy stages through the basic principles of machine code. It shows you how to write simple machine code programs, for example, to add two numbers or flash a message on the screen, and how to load and runa machine code program on yourcomputer. The book is specially written for computers with a Z80 or 6502 microprocessor.* The microprocessor is the chip which contains the computer's central processing unit and computers with different microprocessors understand different machine code. All computers withthe same type of microprocessor, though, use the same machine code. Machine code is difficult and very laborious, with lots of niles to obey and small details to remember. Don’t worry ifyou find it very hard at first. Itseems confusing as you cannot read and understand a program in machine code it’s just a string of letters and numbers. Bugsare very difficult to spot, too, and have disastrous results if you miss them. When youare working in machine code you have to he very carefuland methodical and check everything two or three times. Unless youare really dedicated there is no point in writing long programs in machine code ~ some things can be done just as wellin BASIC. For certain tasks, though, such as speeding up the action in games programs or creating fantastic screen effects, youneed touse machine code. This book shows you how to make your programs more exciting by using short machine code subroutines in BASIC programs. Atthe back of the book there are some conversion charts to help you when youare writing machine code, anda list of machine code wordsto explainall the jargon. There are also lots of puzzles and ideas forshort programs to write, with answers on page 44. 4 “The Spectrum and 2X81 (Timex 2000 and 1000) use the Z80 microprocessor and the VIC 20, the BBC, the Atari computers and the Oric use the 6502, The Commodore 64 uses the 6510 and understands 6502 machine code. What is machine code? Machine codes the code in which the computer does all its work. When yougive acomputer a program in BASIC, allthe instructions and data are translated into machine code inside the computer. Inmachine code, each instructionand piece of information is represented bya binary number. Binary isa number system whichuses only two digits, | and 0, Youcan write any number in binary using Isand Os? Inside the computer, the binary numbers are represented by pulses of electricity, witha pulse fora I and no pulse for a0. The pulses and no-pulses are called “bits”, short for binary digits. The bits flow through the computer in groups of eight and each group is calleda “byte” Each byte of pulses and no-pulses represents the binary number for one instruction or piece of information in machine code. Each task the computer can carry out, such as adding two numbers or clearing the screen, involves a sequence of several instructions in machine code. When you give the computer a BASIC command, a special program called the “interpreter” translates your command into the machine code instructions the computer "You can find out more about binary on page 28. understands Theterm machine code is also used to refer to programs written ina form which is much closer to the computer's code than BASICis. Ina machine code program you have to give the computer all the separate instructions it needs to carry out atask such as clearing the screen, Programming in machine code There are several different ways of writing machine code programs. You could write all the instructions in binary numbers, but this would be very tedious. Instead, you can use another number system called hex, short for hexadecimal. Once you get used to it, hexismuch easier to work with than binary. Machine code programs can also be written in a code called “assembly language’. In assembly language each instruction to the computer is represented by a “mnemonic” (pronounced nemonic)—a shor word which sounds like the instruction itrepresents. 3E isthe hex code for an instruction. This is a program for computers witha Z80 microprocessor. You can find out how the program works later in the book Thisis part of a machine code program in hex, The hex number system has sixteen digits and uses the symbols 0-9 and A-Fto represent the numbers 0 to 15. (Youcan find out more about hex later in the book.) The hex number at the beginning of each line of the programs an instruction (e.g. 3E). Itis the hex equivalent of the binary code for that instruction. Togivea computer a program inassemibly language you need a special program called an “assembler’ which translates the mnemonics into the computer's code. Some computers have a built-in assembler, with others, you can buy anassembler on cassette and load it into the computer's memory. Alternatively you can write a machine code program using the Assembly language LD A isthe mnemonic for an instruction, Thisisa Program to ‘This is the same program inassembly language. Each line contains the mnemonic for one instruction and is the equivalent of the hex number in the same line on theleft, For example, the mnemonic LD A (pronounced “load A”) means the sameas the hex number SE. In both these programs, each line contains an instruction whichis the equivalent ofa single instruction inthe computer's own code. mnemonics of assembly language (they are easier to remember than numbers), then. translate them into hex before yougive them to the computer. Some computers will accept hex numbers; with others you have togive thema short program, called a hex loader”, which translates them forthe computer. There is a hex loader program on page 24 which you can use to load the machine code programs in this book. Getting to know your computer When you programia computer in 5 machine code youhave totellitexactty | Insidea computer what to do at each stage: where to find and store data, how to printonthe screen and soon. (When youare working in BASIC, special programs nside the computer take care of all this for you.) Inorder to give the computer the correct machine code instructions, you needa good idea of what isaoing oninside your computer. The pictures Inside the keyboard of a microcomputer on these two pages show the parts there is a printed circuit board. This has inside a home computer, and whatthey J Metaltracksprinted onit, along which arefor Youcanfindoutmoreabout _| electric currents canlow, Attached to the printed circuit board there are a them on the next few pao fea Nar ofehipe What the chips do This picture shows the work carried out by the different chips inside the computer. Messages flow between the chipsin the form of bytes, i.e. groups of eight pulse and no- = pulse signals representing data and S instructions. The ROM chips Bytes of computer code flow between the chipsalong the tracks ofthe printed circuit board. There are three separate systems of tracks for carrying bytes for doing different jobs. Each system of ROMstandsfor"read only memory". The _ tracks is called a ‘bus’. machine code instructions which tell the computer what todo are stored inthe ROM chips. Itis called a read only memory because the computer can only read the information in ROM, it cannot store new information there. On most home computers, the interpreter (the program which translates BASIC the programs you give the computer are stored while the computer is working on them. It is called a random access memory because the computer can find, or access, any piece of information anywhere in the memory. When you switch the computer off 6y the information stored in RAM is wiped out. ofcircuits inside chip Enlarged wif Printed circuit board The proper name for achip isan instructions in binary code, flowing “integrated circuit” andinsideeachchip _ through the circuits in the chips. There there are microscopicelectrical circuits. _are different chips for carrying out Allthe computer's work is done by different tasks. The work done by the streams of pulses representing different kinds of chips is shown in the picture below. Clock This is a quartz crystal which pulses millions of times a second and regulates the flow of pulses inside the computer. Your computer's microprocessor There are several different inakes of microprocessor chip andall home computers use one or other of them. The most common makes are the Z80, found in Sinclair (Timex) computers, and the 6502, used inthe Oric, the BBC micro, the VIC 20 and many others. Other examples of microprocessors are the 6809 used in the Dragon computer and the 9900 in the TH99/4 ‘The different makes of microprocessor use different machine code instructions, but all computers with the same kind of microprocessor use the same machine code. There are also several different versions of each chip. For example, the Z80A isa faster version of the 280 and the 6502A and 6510 (used inthe Commodore 64) are versions of the 6502. They use the same machine code instructions, though, as the chips from which they were developed. This book is written specially for computers with microprocessors which understand 280 or 6502 machine code. cl chip computer's central processing unit, or CPU. This is where all the computer's work is done. The CPU does calculations, compares pieces of data, makes decisions and also co-ordinates all the other activities inside the computer. The information telling the CPU what to dois in the ROM. The computer’s memory The easiest way to think of the computer's memory is as lots of little boxes, eachof which can hold one byte, 1. one instruction or piece of information inmachine code. Each box in the memory is called a “location”, and each location hasa number, called its “address, so the computer can find any box in the memory Different areas of the memory are used for storing information for different tasks anda chart giving the address where each area startsis called a “memory map’ When you are programming in machine code you have to tell the computer where to find or store each instruction or piece of information. You do this by giving itthe address ofa memory location. You even have to tell it where to storethe machine code program itself, so you need to get to know the memory map ofyour computer. The memory map The picture on the right shows the memory map of a home computer. There should be a map for your computer in your manual. The memory is organized differently in different makes of computer, so your map will look different from this one. The memory map may be drawn asacolumn like this, or horizontally. The address at whicheach of the different areas in the memory starts isgiven alongside the map and it may be a decimal number ora hex number, or both, as here. In this book hex numbers are distinguished by a &sign (ampersand) before the number. Your manual may usea different symbol, e.g. $, %, or #. he hig! is called "RAMTOP”, or on some computers, “HIMEM" BASIC Thisarea holds the interpreter, the program hich converts instructions in BASIC into the computer's binary code. ace RES Ca Operating system This area contains a group of programs called the “operating system” or “monitor”, which tell the computer how to operate, Allthe programs are inmachine code. There are programs which tellit how todo mathematical calculations, programsto clear the screen, find arandom number, scan the keyboard and all the other things the computer has todo inthe course ofits work. Input/output Variable storage { User RAM The boundary between user RAM and \ variable storage | moves up or down \ = depending on how much space's needed for variables, The memory map includes. both ROM and RAM, The operating system and the BASIC interpreter are in ROM and the rest of the areas onthe maparein RAM. Operating system Memory addresses Inside the computer, memory addresses are represented by two bytes of computer code, i.e. 16 pulse or no-pulse signals or “bits”. The largest possible memory you can have ona microcomputer which uses a 280 or 6802 microprocessor is 64K (ROM and RAM combined). ‘This is because the biggest number you can make with 16 binary digits is 65536, so this is the highest possible address. This gives 68536 locations, numbered from 0 to 65535. Each location holds one byte, 1024 bytes make a kilobyte (K) and 65536 bytes equal 64K (65536 ~ 1024 = 64). On the 2x81 (Timex 1000) the boundary between the scree! memory and user RAM changes depending onthe size of the program inuser RAM. Reserved for use of the operating system These RAMlocations are used by the computer to keep track of everything going on while it carries Ifyou add extramemory ‘outa program. For instance, toyour computer, the information about the position of the addresses of some of the cursor, the current screen colour, areas may change. There which key is being pressed and the about this in your manual. current program line number are all stored in this area. It is divided up into smaller areas for carrying out differenttasks, Some computers have a second map of this area. You can find out more about it overthe page. &2400 Inside the computer's workspace ‘This picture gives a closer view of the area of the computer's memory reserved for use by the operating system. There may be a second detailed map of this area in your manual, ora list of the various addresses and what they are used for. On some computers (e.g. Sinclait/Timex), the locations used by the operating system are not in one group andare distributed throughout the memory. User-defined graphics Ifyou make up your own graphics characters they are stored here. Buffers These are temporary stores to hold data coming in from the keyboard, or being sent toa printer or cassette. Machine stack Also called the processor stack, the CPU usesthese locations to store addresses while it is working ona machine code program. BASIC stack Also called the GOSUB stack, this is for storing the line numbers used in BASIC GOSUB and GOTO commands. Calculator stack This is the CPU's temporary store for numbers used in calculations. Systems variables ‘These are a series of memory locations where the CPU stores information about what is happening inside the computer. For instance, there are separate locations for recording the current position of the cursor onthe screen, which key is being pressed and the address of the area where variables are stored. More about stacks The computer uses the stacks to store temporary data in a particular way. The last itemto be stored must always be the first to be retrieved. Thisis called LIFO storage: lastin, firstout Hex numbers Inamachine code program, umbers and addresses are al written inhex, Below you can find out how to convert decimal numbers to hex, and viceversa. Decimal VERE Eee 6 [7 [8 [9 [10/11] 12[13]14]15 Hex o[1[2z[s[4[s5 6i7{[s{alalel{el[po[elr ‘This chart shows the hex digits (0-9and A-F)and their decimal values. To make numbers over 15 (F) you use two (or more) Decimal 1000s | 100s | 10s | 1s, eee Inthe decimal system the first digit onthe rightofa number shows kow many Isthere are, the second shows the number of 10s, the third, the number of 100s (107), etc. Decimal to hex Toconvert a decimal number e.g. 1226, to hex, first you divide by 256 to find how many 256s there are in the number. Then you divide the remainder by 16tofindthe number of 16s and the remainder from this sum gives the numberof ls. Finally, convert the answer to each sum toa hex digit. Converting hex addresses Ina hex address, e.g. 5C64, the two left-hand digits show which page (see opposite) the location is on and the second pair of digits shows the position on the page. Hex to decimal Address &5C64 Page number = &5C = 92 decimal Position onpage = &64 = 100decimal 92 x 256 = 23552 + 100 = 23652 Hex address 5C64 is 23652 decimal. Toconvertahex address to decimal, first convert each pair of digits toadecimal number, as shown above. Then multiply the page number by 256 (there are 256 locations ina page) and add the number for the position on the page. *See page 41 for how todo this on a calculator. digits, just as you do in the decimal system to write numbers over 9. The value of each digit depends onits position in inthe number. 4CAisher) \for 1226, Inahex number the first digit on the right also shows the number of Is butthe next digit shows the number of 16s, and the third digit shows the number of 256s (167). Can you convert &A7to decimal and decimal 513to hex? (Answers page 44.) .. 4is4inhex 1226 = 256 = 4... remainder 202 202+ 16 = 12... remainder 10... . 12is Cinhex 10isA inhex 1226 is 4CA inhex Decimal to hex Decimal address 23652 23652 +256 = 92 (memory page number) remainder 100 (position on page) 92 + 16 = S remainder 12 = &5C 100 + 16 = 6 remainder 4 = &64 Decimal address 23652 is 5C64 in hex. ‘To convert a decimal address to hex you have to divide by 256 to find the memory page number. The remainder gives the position on the page. Then you convert the figures to hex digits as described above ll Peeking and poking Two BASIC words, PEEK and POKE,” enable you to lookat the bytes stored in the computer's memory locations and. change them. You use PEEK and POKE, with the decimal, or on some computers, hex, address ofa memory location. Remember, to give the computer hex numbers you must type a sign suchas &, # (called hash) or $ before the number. Check this in your manualas it varies on different computers and some computers will accept only decimal numbers. Youcan peek into any location in your computer's memory, but you can only poke new bytes into RAM locations because the bytes inROM cannot be changed. Using PEEK These are the decimal equivalents of bytes of computer code. Totell the computer to look ina memory location you use PEEK (or your computer's ‘Try writing a short program using a FOR/ command) with the address of that location, _ NEXT loop, like the one in the centre above, To see the result on the screen, use PRINT to print out the bytes from aseries of PEEK, or tore the result ina variableusing locations. Look at your computer'smemory LET and then print out the variable, as map and experiment with addresses in shown above left. different parts of the memory. Poking This tells the computer to put 60 in location 16763. This puts a number, N, into Use PRINT PEEK location A. to see the result. : The picture above shows youhowtouse _short program like the one above topoke POKE. You can poke anywhere in RAM, but several numbers intoa series of locations in ifyou poke new values into the area user RAM. reserved for use by the operating system The numbers you poke must be between you may disrupt the workings of the Gand 285, the highest number than canbe computer. Youcanrestore ittonormalby _represented with eight binary digits (one switching off and on again. Try writinga byte of computer code). *Some computers use different commands, e.g. the BBC uses? mark. Check your manual. What the numbers mean When you tell the computer to print the contents of amemory location on the screen, the result is always a decimal number from 0 to 258. This is because each memory location can hold one byte, and the highest value that can be represented with eight binary digits is 255. There are only 256 (Oto 265) possible different bytes of computer code and each byte can have several different meanings for the computer. For example, the binary number 00110000 (decimal 48) could be the code for one of the instructions in the instruction set, fora letter on the keyboard, or for part of the address of another memory location (each address consists of two bytes) in your computer's Now find the screen memory for your computer, then try poking numbers into screen memory locations, Youdonotneed touse PRINT PEEK because bytes stored in the screen memory are automatically displayed onthe screen. This time the computer interprets the number asthe code for acharacter.” —_— Put an address in your computer's screenmemory Trya short program like the one above to print your computer's character set. The program uses ASCII codes, starting with 33, the code for!, and ending with code 90. Other numbers in the range 0-256 are for special keys such as SPACE and DELETE, for printing the alphabet in inverse or flashing characters, and for graphics characters. Typein the address for your computer's Operating system Look in your manual to find the address in ROMof your computer's operating system and then try this program. The numbers which appear on the screen are the decimal equivalents of bytes of machine code from one of the programs in the operating system, Thisisthe ASCil code’ forZ. Most computers use the ASCII code (pronounced “askey”), to decide which numbers represent which characters, but some, such as the ZX81 (Timex 1000) use different numbers. The VIC 20 has a special set of numbers, cailed screen codes, for characters to be displayed on the screen ‘There should bea list of your computer's character codes in your manual. Onmost computers you can printa character in a particular position onthe screen by working out the address ofthe location for that position. For example, ifthe screen memory starts at location 1024 and the computer can print 32 characters ona line, the address for the first position onthe fourth line will be 1024 +(32%3) whichis 1120. (Address 1024 is counted as zero.) 8 *On the Spectrum (Timex 2000) the information for each position on the screen is stored in several different memory locations and you cannot print characters by poking codes into the screen memory. Inside the CPU Addtwo Fetch abyte from the memory Allthe computer's work is done by bo and putt inthe fetching bytes of instructions and data the sortof registers. from the memory, then carrying out the instructions instructions in the CPU. puccecam There are three main areas inside the CPU: the registers where bytesofdata are held while they are processed; the ALU, or arithmetic/logic unit where bytescan be added, subtracted or compared, and the control unit which organizes all these activities. The arrangementofthe recistersin _ | These pictures show the sort of instructions the Z80 and 6502 chipsis different, as which the CPU can carry out. They areal shown in the pictures below. lvery simple. It can fetch bytes from the |memory and put them in the registers, move bytes from one register to another, process them in the ALU and store the results inthe The Z80 registers memory. Even the simplest task, such as The main difference between the 280 and the 6502 chips is that the 280 has more registers. ‘This means that bytes can be stored temporarily in the CPU, whereas in the 6502 they haveto be sent back to the memory. Astandsfor“accumulator". Fis the “flags register’ Itholdseight IX and T¥ are called Itisthe most important bits but only six of them are used. “index registers”. register in the CPU and Each bit acts as a signal. For They can each hold storesbytesontheir wayto example, the carry flag is set to 1 Ig bits and they are and from the arithmetic/ when an answer is greater than 255 used in certain logic unit. It can only hold and will not fitin one byte andthe instructions to work one byte ata time. sign flagshows whetheranumberis out the address ofa positive or negative. byte inthe memory. B,C, D, E, Hand Laregeneral SP stands for “stack PCis the “program counter”. purpose registers where bytes pointer”. [tis a 16-bit Ttis a 16-bit register and it can be stored on their way toor register and storesthe holds the address of the next fromthe memory.Eachcanhold addressofthe last itemin byte to be fetched fromthe only one byte but they canbe the machine stack -the memory. The number inthe grouped together in pairs, e.g. place where the CPU program counter increases 14 BC,DEorHbtoholdtwobytes. —storestemporarydata. by one each time an instruction is carried out. Transfer a byte from one register to another. Jump to instruction 6. adding two numbers and displaying the result on the screen, involves over a hundred simple steps like these and the ‘CPU can carry out over half a million each second For each operation the control unit fetches an instruction byte from the ROM or The 6502 registers “Flip the bits”) thatis, make allthe Isinto Osandalithe Osinto 1s. Moyeall the bits one place’ tothe right. RAM, loads a data byte into the registers and then performs the operation specified by the instruction. In machine code, you can tell the CPU what to do with the bytes inthe registers, but the ALU and control unit carry| out their work automatically and you cannot tellthem what todo. ‘The main registers in the 6502 are the same as those in the Z80, but some of them are called by different names. Aisthe “accumulator” where bytes are stored on their way to and fromthe ALU. Itisthe same asthe accumulator in the 280 and canhold only one byte. Xand ¥ are“index registers”. They are used in certain instructions to work out the address of a byte of data. They can also he used as general purpose registers to hold bytes temporarily. This isthe ninth bitof the stack pointer {register S) Pstands for “processor status register” and it has the same function asthe flags register inthe 260. It contains eight bits, seven of which are used. Each bits setto ] torecordacenain condition, such as whether a number is positive or negative. PCisthe “program counter" and it works in the same way asthe PCregisterin the 280 Sis the “stack pointer”. It stores the address of tie last item on the stack - the special area in the RAM where the CPU stores data. Inthe 6502 the stack pointer is an eight-bit register. In order tostore addresses a ninth bit kept permanently at 1 is wired up to theS register. This represents the page number of the address, so inthe 6502, the stack is always in page one of the memory. The number in the stack pointer gives the position on the page. 15 16 Giving the CPU instructions A program in machine code consists ofa list of instructions telling the CPU exactly what to do with bytes m the registers. You can use only the instructions that the CPU understands, so ‘or computers witha 280 or Z80A microprocessor you must use instructions from the Z89 instruction set and for computers with a 6502, 6502A or 6510 microprocessor, you must use 6502 instrucuons. There is a list of Z80and 6802 instructions at the back of this, book. Most machine code instructions consist of two parts: an “opcode” and an “operand”. The opcode tells the CPU what to do and the operandtells it where to find the datato work on. (The word operand means “object on which an eperation is performed”.) Each opcodeis an instruction from the instruction set short words which represent what they do— oras the hex equivalents of the computer's binary code for each instruction. For example, LD A onthe Z80 and LDA onthe 6502 are the mnemonics for “load a byte into the accumulator”. The same opcodes in hex are SE for the 280 and A9 for the 6502. Here are two machine code instructions in mnemonics, one for the Z80 and one forthe 6802. They both tell the computer to load the number 05 hex into the accumulator (& isthe *You can find out about assemblers on page 40, Mnemonics are much easierto understand then hex, but you cannot type them into your computer unless you have an assembler (a program which translates the mnemonics into the computer's own code).* Most people write machine code programs in mnemonics and then translate them to hex sign to indicate hex numbers). Numbers are always written in hex in machine code.On the 6502 a number is preceded bya # (hash) sign to show that itis a piece of data. OPERAND Asimple program Here are two programs, one for the Z80 and one for the 6502, which tell the CPU to add two numbers. They are both written in mnemonics. Strictly speaking, a program in mnemonics iscalled an assembly language program and one which uses hex codes is called machine code. Over the page you can find out how to translate the programs to machine code, and onthe next few pages, how to load and run the version for your computer ‘The 280 and 6502 programs follow the same steps, although the actual instructions are different. * In the 6502, data on which calculations are to be carried out must always be placed in the accumulator. In the Z80 it is placed in the accumulator, or for big numbers, in register pair HL. To add two numbers you load the first accumulator and store the resultin the number into the accumulator. Then youadd memory. The mnemonic opcodes for these the second number to the one inthe instructions are given below. = Opcodes and Z80mnemonics |, Meai Load A witha number. A stands for “accumulator” LD A,number ghd uDisshor for “load” operands for the 280 are separated by commas ADD A,number | AddtoA(the accumulator), a number. | Load a certain address with the contents of A (theaccumulator), LD{address),A | adresses are always written in brackets, i {6502mnemonics | Meaning Load A withanumber. A stands for “accuinulator” and LDis short for LDA number ae ADCis the mnemonic for the instruction “add with carry”. It tells the ADC number computerto add anumber to the accumulator and to set the carry flag in the flags register if necessary. You can find out more about this on page 29. | Store A (i.e. the contents ofthe accumulator) at a certain address. STis SEE short for “store” and A stands for “accumulator”. ae ——— - his program uses ign indi 280 adding three opcodes: LD A, thatthe Qperand is program ADDA, and jece of Gata. LD address), A. , ° LD A,802 ADD A, &04 Spaz LD (87F57),A Now you canfillinthe dataandaddresses. and 4 decimal), and storing the result in Inthese examplesthe programsareadding memory location 7F57 hex 2hex and 4 hex (which are the same as 2 *From now on, if you have aZ80 you can skip over the 6502 programs and if your computer uses 6802 instructions, ignore the Z80 programs 18 Translating a program into hex ‘The only way to translate the mnemonics into hex codesis to look upeach mnemonic ina chart. The isa chart of mnemonics and hex codesat the back ofthis book. You have to be careful, though, as there are several different hex codes for each instruction depending on whether the operand isa piece of data, an addressor the name ofa register. Fi When the operand is apiece of data itis called “immediate addressing”. Whenit is the address where the datais stored itis, called “absolute addressing”. The list of mnemonics and hex codes at the back of xample, here are some different versions of the opcodes for loading the accumulator, and ir hexcodes. this book includes all the instructions covered in this book. If you want to write more advanced programs you will need to geta complete list of 280 or 6302 codesand there are some suggested books on page 40. 280 adding program 6502 adding program Mnemonics Hex codes | Mnemonics Hex codes LD A,data 3E, data | LDAdata | Aodata “ADD A,data | c6,data | apcdata Jesaata | LD(address),A | 32, address STA address | sD address Here are the hex codes for the Z80 and 6502 adding programs. Instructions in mnemonics are sometimes called source code and those in hex are called object code. 280 adding program with data 6502 adding program with data Mnemonics Hex codes Mnemonics Hex codes LDA, &02 3E, 02 LDA #&02 AS 02 “ADA, &04 |e, 04 eed ADC #804 | 69 04 LD (807F57), s | 32,577F | STA &7F57 : Slepra77pee nee | Now you can fill in the data and addresses. This is quite straightforward - except for the addresses. In machine code you have to. reverse the order of the two pairs of digits which make up an address. You can find out, more about this on the opposite page. [You have to reverse the two pairs of digits in an address, like this. You leave out the & and # signsin the hex code version. More about hex codes ‘Machine code programs are written in hex rather than decimal numbers because the binary numbers used inthe computer's own code translate more neatly to hex than decimal. FFE FE beeina tbe oeima Hex number that can be represented by one byte (eight binary digits) is 255 decimaland FF hex.” For example, the highest address you can have with sixteen binary digits is 65535 in decimal and FFFF in hex and the highest Most of the opcodes in the computer's instruction set are one byte long, soin hex each opcode is two digits. Addresses, though, take up two bytes so they need two pairs of hex digits. ‘The first pair of hex digits is called the high order byte andit is the page number inthe memory on which the address is located (see page 10). The second pair of digitsis called the low order byte and itis the position of the memory location on the page (one page = 256 memory locations). Because of the way the CPU handles addresses you must always give it the low order byte (position on page) first, followed by the high order byte (page number) Looking at machine code programs Machine code programs in magazines look very confusing until you work out how they are presented. Below there are two examples of the way machine code listings are displayed. (Neither of these programs is complete and will not work on acomputer.) Hexdump — E&chpairofdigtsisan inhex. 00 30 ca co 538 3a Fa ey Assembly language listing Address Hexcodes nen ra Lox “#200 LDA LOSAE, x 0345 9D CO 8S STA UBSCO,X os4a Es INx 0349 £0 0348 DO BNE 4F5 0540 00 BRK 0340 a2 00 0342 BD 4E 03 #208 Thisis called a hex dump. The first four digits in each line are an address andthe restof the pairs of digits are the hex codes for instructions, data and addresses. The first code in each line is stored inthe address at the beginning of the line. The rest of the codes are stored inthe locations following that address. ‘This listing includes hex codes and mnemonics, The first number in each line isthe address where the first byte ineach line is stored in the computer's memory. ‘Thenext column contains the hex codes forthe program, followed by the mnemonics. 19 *You can find out how to convert binary numbers to decimal on page 28. 20 Finding free RAM There are several things to do before you can load and run the adding programon page 18. First you need to choose an area in the memory in whichto store the program. When you type ina BASIC program, the BASIC interpreter automatically stores your program in user RAM. When you give the computer a machine code program, you bypass the interpreter so you have to tell the computer where to store the program. You need to choose an area in the RAM where your machine code will not interfere with any other information stored in the memory. For instance, youmnust no! store machine code in the areas reserved for use by the operating system, such as the systems variables or the stacks. If you do the system will probably crashas your machine code will have replaced vital information which the computer needs to organize all its work. Youalso have to be careful to keep your machine code separate from any BASIC program you may give the computer at the same ume If the computer crashes the only way to restore it is to switch it offand on againand you will lose your program, How much memory will you need? Each memory location holds one byte. Itis quite easy to work out the length ofa Most machine code programs are quite machine code program -youjustcountup short and tostart witha hundred bytesof the number of pairs of hex digits(eachpair memory space will probably be plenty ior takes upone byte), For example, theadding your machine code programs, program has seven bytes. Finding free RAM The normal place to store machine code programs is at the top of user RAM, the place where BASIC programs are stored. You have to make sure, though, that the machine code will not get mixed up with any BASIC programs. To avoid this you can lower the top ofthe user RAMarea. This makes a “no-man’s land” above user RAM which the computer will not use until you tell itto when you load your machine code program. The top of user RAMis called RAMTOP, or HIMEM, or just top of memory. You can find out how tolower RAMTOP on the opposite page. Lowering the top of user RAM The computer keeps a record of the address of RAMTOP in the systems variables and you can change RAMTOP by changing the address stored in the systems variables. The instructions for doing this vary on different computers, but most follow the principles given below. You should check how to change the top of RAM in your manual though, as your computer may use different instructions, or may even have an easier way tomake space for machine code. TL SYSTEMS VARIABLES J = teat froop | = Bye MAe vi ‘The address of RAMTOP takes up two consecutive locations in the systems variables, one for the page number of the location and one for the position onthe page. Look up the addresses of these systems variables locations in your manual (they may be listed as RAMTOP, HIMEM, or Position just top of user RAM). The computer stores the two bytes of the address inreverse order — first the position on the page, then the page number, so the first location in the systems variables holds the position number and the second, the page Youcan use PRINT PEEK (or your computer's command) like this to peek into the systems variables and print out the address of RAMTOP. Fill in the addresses of your systems variables, ‘Most computers have their own special command for changing the address of the top of user RAM. For instance, for the Spectrum (Timex 2000) the command is CLEAR and for the Oricitis HIMEM, These commands are followed by the address of the top of user RAM minus the number of bytes of memory you wish toreserve for This command automatically converts the two bytes of the RAMTOP address intoa decimal address by multiplying the page number by 256, then adding the positionon the page. machine code as shown above left. Check your computer's command in your manual. These commands lower the top of user RAM by 100 locations and so reserve an area of 99 bytes for machine code starting at the address after RAMTOP. Youcan change the figure 100 to reserve more space. al *See over the page for how tolower the top of RAM onthe VIC 20, and where to store machine code onthe ZX6 | (Timex 1000), 22, VIC 20tip The VIC 20 has no special command for changing the address stored inthe systems variables. Here are the instructions for lowering the address of the top of user RAMon the VIC. YSTEMS. VARIABLES | ‘The address is held in systems variables §5and 56. Remember, the second location holds the page number. ‘To lower the top of user RAM by 256 locations, i.e. one page, use the direct command shown above. This makes the computer peek into location 56 (the one which holds the page number). It subtracts 1 from the value held there and then pokes the new value back into location $6. In other words, it reduces the page number part of the address by 1. To see the new address of the top of user RAMtype this command: PRINT PEEK(55)+PEEK(86)*256. 2X81 tip Onthe 2X81 the best place tostore machine code programs is atthe begiming ofuser RAM. To do thisyou type a REM statements the firstline of the hex loader program given on page 24 and fillit with as many digitsas there are bytes inyour machine code Program. Each of the digits inthe REMstatement takes up one location inthe memory. Now you can poke your bytes of machine code into the locations reserved by the digits inthe REM statement. The first byte of machine code will be stored in location 16514, location 16509, Todothis youneed to know the address where the first dicitis stored. User RAM startsat location 16509 and the computer needstwo bytesto hold the REM line number, one for REM, one for NEWLINE and one torecord the length of theline, so the first digit is in location 16514. Other places to store machine code ‘There are a few other places inthe memory where you can store machine code, if you are not using them. For instance, ifyou arenot planningon saving your program, you can store itin the cassette buffer, or if youare not creating any user-defined graphics, you could store itin the area set aside forthis. Look in your manual to find the addresses of these areas inthe RAM. ‘Your manual may also suggest suitable places in your computer's memory for storing machine code. You should look ‘Out, too, for tips in: magazines andbooks: User defined graphics area. Loading and running a program The next few pages show you how to load and run the adding program on page 18. To give the computer a machine code program you have to poke each byte into the area of memory that you have chosen for storing machine code (e.g. above RAMTOP). On most computers you can only poke decimal numbersso you use a short BASIC program called a "hex loader” to do this for you. The hex loader converts each byte of machine code toa decimal number, then pokes it into the memory. There isa hex loader program over the page. First, though, you need to. change the address for the answer to the adding program, to an addresssuitable for your computer. There isalso one more instruction (see below) you must add to the program. Choosing an address for the answer Data produced by a machine code program, suchas the answer to the sumin the adding program, is called “data bytes” Itis important to store data bytes where they will not get mixed up with the program itself. The best place is right at the beginning of the area you have reserved for machine code, in front of the program. EGREEE For example, if you have lowered the top of user RAM to, say, location 16000, the first address of the area for machine code will be location 16001. This is where you would To convert the address to hex you divide by 286. The answers the decimal page number and the remainder is the position onthe page (see page 11). The return instruction store the data byte and the program would start in location 16002, You will need to convert the address for the data byte to hex so youcan insert it in the program. Address 16001 is 381 in hex. To convert these to hex you divide by 16 and then convert the answers and remainders to hex digits as shown above. 280 mnemonics Hex codes LD A, 802 3E,02 ADD A, &04 6,04 LD (&7F57),4 4 |} . 32,577F ORES At the end of every machine code program you must always have the instruction RET (for the 280) or RTS (for the 6502). This makes the computer stop runningthe machine code program and retum to where 6502Mni LDA #&02 ADC #804 STA &7F57 itleft off. Without this command, the computer would carry on attempting to follow an instruction for every byte it found inthe memory and the system would soon crash.* 23 *There is more about the retum instruction on page 35. Hex loader program Here is the program for loading machine code into the computer's memory. To use this loader yon put the hex codes of your machine code program in line 160, followed bythe ‘word END, asa signalto tell the computer there is nomore data. At ine 40, the computer readsa pair of hex digits, converts them to a decimal number in lines 70to 110andthen pokes that number into the memory inline 130.* 10 PRINT “ADDRESS WHERE MACHINE De eae ee LORE PS, Aisthe address of the first location where 20 INPUT A you wish to store your program. 30 LET b=0 ‘Cisa counter. 40 READ He Puts first pair of hex digits in line 160into HS. 50 IF Hé="END" THEN GoTo 180 ———_—— Tests HS for word END, the signalto 60 TF LEN(HS)¢>2 THEN GOTO 170 ae Beet caeciviching) aise ~~ L_— checkstomake sure Hi contains wo digits, a and ifnot, goes to line 170. 80 IF ASC(HS)257 THEN LET X= ‘Converts first hex digit to a decimal number (ASC (HS) -55) #16 and stores in X. 90 LET Y=ASC (RIGHTS (HE, 1) 100 TF Y¢58 THEN LET 110 IF YoS7 THEN LET Converts second hex digit toadecimal number, Y, and adds toX. Checks for bad data by making sure 120 IF X25S THEN GOTO 170 ——— decimal number in X is between 0 and 258. 150 POKE Aec.x ———______—_ First ime, C=0, so pokes Xinto memory location A. 140 LET G=C+1 —______________— Adds one to C, sopokes decimal value of 150 GOTO 40 next hex code into memory location A+1. ieee eae eee ey rae 155 REM SAMPLE DATA ONLY Baek ares neni peg cae Put your hex codes here, followed by signal word END. 170 PRINT “BAD DATA” ———_—— Prints this fit finds bad data in lines 60 or 120, then stops. 160 DATA EF.Fé,£2,a9, END 180 STOP How the loader works Atline 80 ituses the same method to Atline70,the computer convertsthe first _convertthe right-hand digit to an ASCIL digit in H$ to its ASCII code usingthe BASIC code and storesitin Y. In lines 100 and 1 1Cit word ASC. Itthen convertsthe ASCIIcode changes Y toadecimal number by toadecimal value by subtracting 48, orfor _ subtracting 48 or §5 as before, and addsitto ‘codes over 57, by subtracting$5,asshown _X. (Thistime it doesnot multiply by 1éas itis inthe chart above. Then it multiples by 16 the digit which represents Is in the hex because the first hex digit represents the number.) The value stored in X isthe number of 16s and puts the answer in X. decimal equivalent of the pair of hex digits. *For the Spectrum (Timex 2000) change the ASC command to CODE and put each pair of hex codesin quotes. See page 48 for alterations for the 2X81 (Timex 1000) and Atari computers. Using the loader Now you can use the hex loader to try out the machine code adding program. This is nota very exciting program, but itis simple and it shows you how machine code works. Typethe hex loader into your computer. At line 160, replace the sample data with the hex codes for the adding program, as shown below. Data for the hex loader Ta Replace Ib and hb with the two END signal bytes of the address for the tocomputer. answer. 6502 | 160 DATA A9,02,69,04,8D,1b,hb, 60,END These are the hex codes for theadding answer will be stored m your computer. program. Youneedtoreplacethe letterslb Rememberto putthe bytes in reverse (low order byte) and hb (high orderbyte), _ order, i. low order byte (position on page) with the two bytes ofthe address wherethe _ followed by high order byte (page number). Running the hex loader RUN ADDRESS WHERE MACHINE CODE 1S 10 BE STORED? 716002 Now type RUN to run the hex loader youare storing the answer. Type this program. When itasks youfortheaddress, _addressas adecimal number asit willbe type inthe first location after the one where —_ used with the POKE command. Running the machine code program CALL 16002 PRINT USR( 16002) SYS (16002) See hese are some of the commands used on different computers. The command to tell the computer tostart first byte of the programis stored. Check running a machine code program varieson __ this command in your manual. When the different computers. Some use CALL, computer receives this command it goes to others use PRINT USR or SYS with the the address and starts carrying out the decimal address of the location where the machine code instructions. 28 Seeing the result PRINT PEEK (16001) PRINT PEEK (16001) 6 The computer carries out the machine code _have touse PRINT PEEK with the address of instructions and stores the answer inthe the answer, The result will be the answer in location youtolditto. Toseetheresultyou decimal, Programs to write ‘ou now know enough machine code to write some simple programs. There isa checklist at the bottom of the page to help you remember all the things you have todo when you write a machine code program. Answers page 44. 1. Try writing a program to add 25 and 73 (decimal) and store the result inthe memory. 2.See if you can write a program toadd |64 and 12 and 14 (decimal) and store the | result in the memory. The adding program will only add numbers which total less than 255. On page 28 you can find outhow to add larger numbers —— a a Machine code checklist 1, Write your program inassembly language and convert any data to hex. 2. Look up the hex code for each of the mnemonics (there is alist of the mnemonics and hex codes at the back of the book). 6. Fill in the addresses in the program— remember to put the two bytes in reverse | order. (See pages 18-19.) very carefully. Don’t forget to put END after your list of hex codes in the hex loader. 7. Type inthe hex loader (you could save this program on tape) and fill in the hex codesin line 160 followed by the END signal, (See page 24.) 3, Add the return instruction tothe end of the program, (See page 23.) 4. Count up the number of bytes and reserve your free RAM area, (See pages 20.22.) Makeagioleontheacdiestecor 8, Run the hex loader and inputthe data bytes and of the address decimal address of the first location where you havestored the where you wish to store the machine ere code. (See page 25.) 9. Run the machine code program using your computer's command withthe address (in decimal) of the first location where the machine code is stored, (See page 25.) Ifyou change the data in the hex loader you have to run the program again to poke thenaw bytes into the memory 5. Work out what memory locations you need for data bytes and convertthe 26 addressesto hex. (See page 23.) Adding bytes from memory Inthe previous program the data was included in the program itself. This iscalled immediate addressing. Sometimes, though, you may want to tell the computer to dosomething with data stored m its memory. In this case, the operand part ofan instruction will be an address telling the computer where to find the data. Thisis called absolute (or direct, or extended) addressing. Immediate Absolute addressing addressing These are just two of the several different modes”. There is a different hex code for ways in which you can tell the computer each instruction depending onthe where to find the data to work on. The addressing mode youare using. different ways are called “addressing Program to add numbers from the memory Here is a program to add two numbers stored in the memory. Compare the hex codes for the instructions in this program, which uses absolute addressing, with those forthe previous adding program which used immediate addressing. 80 program Mnemonics Hex codes | Meaning [LD Avfaddress 1) | 3A, address 1 Put the nuriber in address 1 into the accumnulator. LD B.A 47 Put the number in the accumulator into register B. [LD Avladdress2) | 3A,address2___ ADD A,B a | LD(address3),A | 32, address3 the content ori | RET [co [ Rerum Toadd two numbers from memory you straight from the memory, though, so you have to load them intothe registers first.For have to put the first number into A andthen this you canuse the accumulator (A)and _ transfer ittoB. register B. You cannot load register B Running the program Torun this program, follow the steps given in the checklist on the opposite page. First, though, you will need to poke into the memory the two numbers to be added. Youshould choose memory locations at the beginning of the area you have cleared for machine code, to keep these data bytes separate from the instructions, Then convert the addresses to hexand. insert them in the program. You needa third address for the answer. To see the result, type PRINT PEEK(address 3). a7 28 Working with big numbers ‘The programs on the previous few pages only work with numbers which add upto 288 or less. This is the highest number that you can represent with the eight bitsin one register or memory location. To work with larger numbers you need to knowa little more about the binary number system and how to use the carry flag. Overthe page there isa machine code program to add larger numbers. Binary numbers ‘The binary number system works like hex and decimal numbers except that there are only two digits, 0and 1. To make numbers bigger than you use several digits and the value of each digit depends on its position inthe number. 11111111 binary is 255 decimal. x128 <64 x32 x16 x8 x4 x2 x1 128 +64 +32 +16 + 8 +4 +2 + 1 =255 Inabinary number, eachdigithastwice the third, the number of fours; the fourththe the value of the digit on its right. Thefirst number of eightsand soon, as shown above. digit (the one on the right) shows how Toconverta binary number to decimal you many onesthereareinthe number. The — multiply each digit by the value of its position second digit showsthe number oftwos; inthe number and add up the answers. Can you convert these te) TE] Sdecimai? (Answer page 44.) HIZB X64 132 X16 XB x4 x2 1 %128 X64 x92 x10 x8 x4 x2 x1 12H + 0404040444241 =135 Here are some more examples which show how you convert binary numbers to decimal. Giving the computer big numbers Inside the computer, numbers over 255 are stored in two bytes, called the “high orderbyte” and the “low order byte’, just like addresses. The high order byte shows how many 256s there are in the number and the low order byte is the remainder. As with addresses, the computer always deals with the low order byte before the high order byte and you haveto store themninthat order in the memory Togive the computer anumberover255 _‘Ifyouwant touse the numberas dataina you have to work out the value for each machine code program you have toconvert byte. Todo this youdivide the numberby _ each byte tohex. To do this, divide each 286. The answeristhe decimal value ofthe __ byte by 16, then convert the answers and high orderbyte, Theremainderisthelow remainders to hex digits as described on orderbyte. page 1] Whatare the decimal high order and low order bytes for thesenumbers? ‘And what are they in hex? (Answers on page 44.) 307; 21214; 759; 1023. The carry flag ‘The carry flag isa single bitin the flags register (also called the processor status register), which is used to indicate when the answer toa sumis greater than 288 and will not fit intoone byte (eight bits). Whenever this happens the computer automatically putsa | inthe carry flag. This iscalled setting the carry flag and making it 01s called clearingit You can think of the carry flagasa ninth bit indicating that a binary | has been carried over from column eight of a number. For example, look atthe sum 164 + 240 (10100100 + 11110000 in binary), below. imal Binary Toadd binary tumbers you carry each timea column totals more than 128 64 32 168421 Tjustas you do in decimal addition 164 Nm 1 © 1 00100]( whenacolumn totals morethand. +240 urate. 0, 0.080 404 “2110 0 10100 The answer to this sum is 404 which takes up nine bits in binary. The ninth bit shows how many 256s there are inthe number. In Carrying inthe Z80 ‘The 280 has two different adding instructions: ADD and ADC. ADD tellsthe computer to add two numbers but to ignore any carry over from previous calculations. Ifthe calculation results ina carry over, the computer will set the carry flag and there is no carry it will make the carry flag 0. The 6502 has only ore adding instruction, AADC, s0 it always includes the contents of the carry flag in caiculations. Because of this the computer it would be represented by the bit inthe carry flag. ADCstands for “add with carry" andit tells the computer toadd two numbers plus the carry flag, and to set or clear the carry flag depending onthe result. If youare doinga series of calculations itis best touse the ADD instruction for the first sum tomake sure you do not include a carry left over froma previous operation, and then touse ADCin case there was carry from the first calculation. | Youcan see howthe { carry flag works in the program over the page. itis important toclear the carry flag using the instruction CLC (clear carry flag) before you do any additions. 29 Big number program Before you can run the programso and low byte for each of the numbers you memory. For example, say you want to ad Firstnumber: 307 High 307 + 256 = 1 remainder 51 byte Second number: 764 764 = 256 = 2remainder 252 Low order Next you need to poke these bytes into memory locations at the beginning of the area you have reserved for machine code. For eachnumber, the low order byte must be in the first location, followed by the high order byte. Inthe picture above, the two 280 big number program Ss n these two pages you need to work out thehigh want to add and d 307 and 764. poke them intothe High order byte Loworder byte bytes for the first number are stored in locations W and W1 and the bytes forthe second number are in locations X and X1. Youneed three locations, Y, Yl and Z forthe answer (one for the low order byte, one for the high order byte and one fora possible carry), Adding the two numbers on the Z80 is quite easy as you can use the registers in pairs, with each pair holding the wo bytes for one number. You can use the Hand L registers asone pair and the B and C registers as another. When they are used like this they are referred to as HL and BC. When youare not using the accumulator you use the HL registers foradding. Here are the mnemonics and hex codes for th e program. It may help you to look atthe picture at the top of the page when you study this program, Mnemonics ‘| Hex codes Meaning LD HL, (addressW) | 2A, address W ED 4B, address X \ This opcode is | LD BC, (address x) Puts byte from address W (low order byte of first number) into register Land byte from address W1 (high order byte, first number) into register H. Puts byte from address X (low order byte, second number) into register C and bytefrom. address X1 (high order byte, second number) twobyteslong. | into register B. Al 0% | Rdds contents ofHL and BC andleavesresultin | eee 2 ‘HL. itdoes not add in the carry flag but it does set | ___thecanyflagifnecessary. Stores low order byte of answer in address UD(addressY),HL_| 22,address ¥_ eaheoce eae UD A,&0 3E,0 5 " | See opposite pageforhowthe // See opposite for AOC A, &O CE,O computer checks the carryflag. | howto display LD{addressZ),A | 32addressZ i BYES ( theresult ot ier com Rei = this program ~~ \ Torunthe program you need to ill inthe hex addresses for W, X, Y andZ. (Don't forget to reverse the pairs of digits.) When 30 youuse the registers in pairs you need only specify one address for each pair. The computer automatically puts the byte from thenext consecutive address into the other register in the pair Checking the carry flag e Add with ea carry. 0. Lines 5-7 of the 280 program are for accumulator (Sth line), then add 0, using the checking the carry flag. Youcannotloadthe add with carry instruction, Ifthe carry flag contents of the carry flag straight intoa was set by the previous calculation the register, or intothe memory. The only way accurnulator will now contain I (from the tosee ifit has been set isto doanother carry flag) and this isstored in address 2 addition. To do this you put 0 into the (Ith line), 6502 big number program Here is the program for adding numbers greater than 255 on the 6502. Before you mun ityou need to work out the high order and low order bytes for the two numbers and pokethem into the memory as described on the opposite page. Mnemonics Hex codes CLC 18 LDA addressW | AD address W Al STA addressY_| 8D address Y LDA address Wi| AD address W1 ADC address Xi| 6D address X1 8D_address 1 69 00 STAaddressZ__| 8D _addressZ RTS 60 Coe Ms First the program ‘Then it putsthe low order byte of thefirst_ Ifthe resultis greater clearsthe carry flag number intothe accumulator andadds —_than 28Sitsets the incaseitwassetby _ withcarrythe low order byte ofthe carry flag. apreviousoperation. _ second number (2nd and 3rd lines). Pty) Itstores the result in location Y (4th line). Then it adds the two Lines 8-10 check to high order bytes and the carry (if there was one) fromthe see ifthe carry flag previous sum. It stores the result in location YI (7thline) was set using the same - method as shown at Seeing the result the top of thepage. ‘The resultis stored asthree bytes. The low order byte (location ¥) shows the number of units. The high order byte (location Y1) shows the number of 256s. This time thecarry eee a ie; can ada pt an e prog fam | (location Z) shows the number of 65536s. To on page 27 so tnatt can cope wih see the result use the instruction shown onthe heed to add lines to check the carn right. (Replace Y, Y] and Z with your computer'saddresses.) Displaying a message on the screen The next program shows you how to use machine code to display a message onthe screen. The program for the 280 ison the opposite page and the one for the 6502 ison page 34. The two programs follow the same basic principle slightly different for the different microprocessors.* How the program works First you poke the character code foreach ofthe message you poke in the code 255asa letter of your message into locations atthe __ signal totell the computer this is the end of beginning of your free RAM area, Each the message. Are they, equal? 5 SeaEE letter takes up one byte. At the end cLatemony A> The program loads each byte of the message into the accumulator displayed onthe screen. Thenthe and compares it with 255. If the byte of computer jumps back to the beginning of message does not equal 256, itstoresitin _the program to find the next byte ofthe thescreen memory and itisautomatically__ message inthe memory. Comparing things i] 4 aa Zero flag Yowuse the opcode CP onthe Z80andCMP result is0, the two bytes are equal and itsets onthe 6502 tc tell the computer tocompare —_ the zero flaginthe flags register to 1. Ifthey abyte with the one inthe accumulator. The are not equal the zero flag is 0. Youcanthen computer compares them by subtracting _tellthe computer to go to another part of the one from the other. (This isjust atest,infact, program, or carry on with the next instruction 32. thetwo bytes remain unchanged.) Ifthe depending on whether thezero flagis 1 or 0. *Onthe Spectrum (Timex 2000) you will not get a legible message on the screen because of the way the screen memory is organized, Z80 message program Here are the mnemonics and hex codes for the Z80. Before you run the program, poke your message into free RAM. Then fill in the addresses in lines | and 2 of the program. The last instruction of the program tells the computer to jump back tothe third instruction ‘You need to insert the address where the third instruction will be stored in your computer, intothe last line of the program. Mnemonics Hex codes This is immediate LD Hl,screenaddress_|_21,screenaddress addressing — the operands, [LD DE, message address | 11, message address | | “1 the data to be loaded into [ED_A, (DE) GA the registers CP.&FF | FELFF a RET Z C8 ‘LD (HL)A 1 Inindirect addressing the [ING, DE 13 operand is written in INC, HL 23 brackets \[IP address of rd \C3,address of ard — ce instruction instruction / Inthis program, register pairs HL and DE are used as pointers to the addresses where the computer should store or fetch data. This is called “indirect addressing’. The instructionsin the third and sixth lines use indirect addressing. Inthe first two lines, the computer puts the screen address (the address where data isto be stored) into register pair HL and the message address (the address from which datais fetched), into register pair DE. | Address of |__frstbyte of message , j LD A, (DE)tells the computer to read the &FF (the hex for 255), RET Ztells the address in DE andthenfetchthe bytefrom computerto return to BASIC if the zero flag that address and put it in the accumulator, is | (.e. ifthe byte equals 255). Ifthe zero Thisis indirect addressing, Then it flagis0, it carries on withthe next compares the byte inthe accumulator with instruction. SCREEN eh mu LD (HL),A also uses indirect addressing. It increase by one. In the seventh and eighth tellsthe computer \oread the address inHL —_ lines the computer adds one tothe and then store the contents of the addresses held in DE and HL so that whenit accumulator (the message byte) at the jumps back to the instruction in the third location with that address. INC isthe line, it fetches the message byte fromthe mnemonic for “increment” and means next memory location. 33 34 6502 message program Here are the mnemonics and hex codes far the 6502. Before you run the program youneed to poke the character codes for your message into free RAM, followed by 255, the signal for the end of the message, Then put the address, in hex, of the first location where the message is stored, in the second line of the program, Put an address in your computer's screen memory inthe fifth line Youalso need to fill in the seventh line with the address where the second instructionin the program will be stored in your computer, This makes the computer jump back to repeat the program. = in the fourth line of Mnemonics Hex codes the hex codes the LDX #800. A200 9 figure 07 tells the LOA message address, X BD message address computer how CMP #&FF COFF many locations to BEQ toRTS instruction F007 jump to reach the STA screen address, X ‘9D screen address RTS instruction INX 8 Hie) JMP address of 2nd instruction] 4C address of 2nd instruction| RTS 60 This program uses another addressing mode, called “indexed addressing". In indexed addressing, the contents of the X or ¥ registers are added to the operand to give the address where the datais stored. The second and fifth lines use indexed addressing, Codes Beoe Dania le Inthe first Ine, the computer puts 0 into the Xzregister. The second instruction uses indexed addressing so the computer adds the contents of the X register to the address CMP in the third line makes the computer compare the byte in the accumulator with &FF (hex for 288), the signal for the end of, the message. If they are equal it sets the zero flag to 1. The next iristruction, BEQ, stands for “branch if equal’ (ie. ifthe zero Toa a Pelee given inthe instruction. The result givesit the address of the data to be loaded into the accumulator (a byte of message). —— Sevenbytes aro hag is 1) Inthe hex codesitis followed bya number telling the computer how many locations to jump. We want the computer to branchto RTS if the message byte equals 258 and there are seven bytes between the branchinstruction and RTS. aS Next, in the fifth line, the program uses indexed addressing to store the byte inthe accumulator (the message byte) at the address given in the instruction plus X, INX stands for “increment X" and it makes the computer add | to the contents of the X register. Then it jumps back tothe second instruction. This time X is 1, soit loads the next byte of the message into the accumulator and stores it at the next screen location. Jumping and branching Making the computer go to an instruction in another part of the program iscalled branching. There are three different ways of branching: jumps, subroutinesand conditional branches. Ina conditional branch the computer carries outa testand then branches, ordoes on with the next instruction, depending on thé result ofthe test. You can find out more about conditional branches over the page. Jumpsyusttell the computer to go to a certain address. The program counter The program counter is a special 16-bit register which holds the address of the next instruction the computer is to cary out, The computer reads the number in the program counter and then goes to the location with that address to fetch its next instruction. Thenthe program counter is increased by one so it points to the next memory location. 56) 1574 159] When you tell the computer to jump or branchtoacertain address, that addressis sequence from that address. The opcodes put in the program counter and the fora jump on the 280 and 6802 are shown in computer then carries out the instructionsin _ the picture above. Subroutines The instruction “CALL address" on the 280 and “JSR address” (jump to subroutine) onthe 6502, tell the computer to goto a subroutine. This is just like in BASIC and at the end ofthe subroutine you need the retum instruction (RET on the 80 and RTS on the 6502), When you tell the computer togotoa instruction after CALL or JSR) are stored or subroutine, the address of the subroutineis “pushed” on the stack. The stack is a special putin the program counter. The contentsof _ part of RAMset aside for the computer'suse the program counter (the address of the (see page 10). When the computer reaches the RTSor RET Thisis the address of the instruction after instruction at the end ofthe subroutine, it _ the one which sentit to the subroutine. This retrieves, or “pops”, the last item off the is also what happens when youtell the stack and puts it in the program counter. computer to nun a machine code program. 36 Conditional branches Ina conditional branch the computer tests one of the bits in the flags register andthen, depending on the result, either branches or carries on with the next instruction. Here arethe bits in the flag register which you can test in conditional branches : NorS||(@ Z Thisisthezero flag anditissetto | iftwo pieces of data are equal. V NorSThisisthesign Vor P/V Thisis called the overflow bit onthe 6502. C Thisisthe carry bit.tisreferredtoasN On the Z80 it has two functions and is called the flag. Itis set to 1 onthe6502andSonthe _parity/overflow. Asan overflow bititis setto lwhen wher the answer to 280.Itis settolwhen the result ofa calculation in two's complement sum will not fit in theresultofa notation (see opposite) results inacarry overtothe _onebyte calculation isnegative sign bit. and 0 for positive ‘Asa parity bit itis set to | ifthere is an odd number results. ofones ina byte and jsused for checking purposes, Various instructions in addition tothe on the 6802 the instruction DEC compare instruction cause these flagstobe — (decrement) affects the sign and zero automatically setor cleared. Forexample, _ flags." Conditional branch opcodes Hereare the conditional branch instructions for testing each bit. there isa carry (C = 1). : there isa carry (C= 1). sno carry (C = 0) equal (Z = 1) sweushot eqqual (Z = 0) minus (S = 1) -plus (S = 0) -Parity odd (P/V = 1) PPE svnennsesParity even (P/V = 0) oe) UP Caddress }f 1. cage! 280 overflow set (V = 1) overflow clear (V = 0) BCS 805 | Bea 305 12) eg LI > PD 280 Jump Siocations if 6502 Taal sera, Branch Slocations if Branch 5 locations if ca there isa carry. carry. Afterthe "JP test” instruction on the Z80you addressing" and the number is calledthe _ give the computer the address of the “displacement”, or “offset” instruction you wantit to jump to. Onthe ‘The Z80 has an additional conditional 6502 you give the computer anumber which branch instruction, “JR test’, which youuse tells it how many locations it has tojump witha displacement rather than anaddress. forwards or backwards to find the JRstands for ‘jump relative” and youcanonly instruction. This is called “relative test the zero flag and the carry flag with JR. *A complete list of your microprocessor's instruction set will tel! you which instructions affect which flags. ( Remember to count Working out the displacement two bytes for an address. When you give the computer a displacement number ina conditional branch, the computer works out the address of the instruction itis to jump to by adding or subtracting the displacement from the program counter. To work out the displacement, count the number of bytes up to and including the instruction you want to jump to. Start atthe instruction after the conditional branch and count that as 0 (because the program counter willalready pointto that instruction). For example, here are two short 6502 programs which show how you work out the displacement. (The method is the same for the Z80.) LOA address CMP #&FF BNEtoRTS STA address RTS LDAH | CM To make the computer jump to the RTS instruction in the example above, the displacementis 3 FF WIBNEY| 03 Y STA' hb: RTS Inthe example below, the displacement tomake the computer jump back tothe ADC instruction is —6. bb LDA #800 ADC #801 CMP #&FF BNE to ADC Count this Ars instruction asd Forwards and backwards jumps For forwards jumps you just translate the displacement into a hex number and insert it inthe program. For backwards jumps, though, the displacement is a negative number and there is noway of indicating negative numbers in eight bit binary. Instead, you use a differentsystem of notation called “two's complement”. Intwo’s complement, the left-hand bit is used asa sign bit. Ifthis bit is 1 the number is negative. Ifit is 0 itis a positive number. Two’s complement I. To work out the two's complement ofa number, say 6 (the displacement forthe program above), first write down the number in binary. 2, Then you change all the 0s to | andthe Is to0. This is called “flipping the bits” or “complementing” a number. The resultis. called the “one’s complement”, 3. Nextadd 1. The resultis the two's complementof the number. 4. Now you need to convert this to hexto insert it in the program. The easiest way to do this is to divide the number down the middle and work out the decimal andthen the hex value of each group of four digits. and 1 make Ocarry 1 Thisisthe two's complement of 6 8s 4s 2s 1s nese a decimal 15 ex F 8s 1 So the hex representation of the two's backwards displacement you can have. complement of 6 is FA and for abackwards jump you insert this number in the program. Intwo's complement, the highest number you can represent is 128, This is the biggest Can you work out the hex forthe two's zomplement of 12, 18and 9? (Answer page 48) ‘The biggest forwards displacement is 127, the highest number you can make with the eighth binary digit set to 0 to indicatea sitive ber. Positive num 37 Screen flash program On these two pages there isa program which swaps two blocks of display onthe screen to make a flashing effect. It shows how simple animation works. The program for the 280 is given below and the one for the 6502 is on the opposite page Atthe end there are guidelines for running the program for both microprocessors 280 screen flash Put very simply, the program swaps the two blocks of the diplay by loading a byte from each block into the registers, then storing the byte from block b in the screen address for block aand vice versa ar} Grriataeeeeen = ERSTE Tere Poon VF jsenoneongeueEep9000e0e0e00000008 VW aooress6 \|Afpc ADDRESS @. The program uses indirect addressing. The _ the program repeats, these are the screen addresses forthe firstbyte ofeach _ addresses of the next two bytes ineach block are stored in registers HL and DE. block onthe screen. The computer readsthe addresses inthese Register B holds the number of bytesto registers each time it loads or storesthe be swapped. Each time the program bytes, After swapping two bytes the repeats, Bis decremented (decreased) by 1 instruction INC (mnemonic forincrement) _ soit acts asa counter. When B=0allthe makesitadd onetoHLandDEsothatwhen _ bytes have been swapped. 280 program n=number of bytes in one block; a=first address of block a; b=first address of blockb. oS Mnemonics Hex codes | Meaning HL holds address LDB,n 06,n Counter. for block a and { DE holds address LOHL, (addressa)__| 21, addressal PutaddressofblockainHL. _) 2, pocen LODE, (addressb) | 11, address b| Put address ofblockbinDE. LOC, (HL) 4E Load Cwith contents of address in HL (indirect addressing). LDA, (DE) 1A Load A with contents of address in DE (indirect addressing). LD (HL),A 77 Store contents of accumulator ataddress in HI, (indirect). LOA,C 79 PutC(firstbyte blocka)intoaccumulator. LD (DE) A 12. Store contents of accumulator at address in DE. INC HL 23 NEE * | Addoneto HLand DE, DECB 05 ‘Decrement B, the counter. i LDA, &00 3E,00 Put 0 inthe accumulator CPB BB Compare B with contents of the accumulator (0). TEB does not equal zero, jump back &F3 locations toload JRNZto dthinstruction} 20,F3 next bytes into registers. F3 is hex for two's complement lee of 13 (see page 37). RET co Return. Filling in the data and addresses addresses a and b Ifyou want to swap the toptwo lines of the screen with the next two lines, make address a the first address of your computer's screen memory, Address b isthe address for block a plusthe | number of bytesto be swapped. Convert both ‘n (number of characters in one block) To find n, multipl “| the number of characters in aline by the number of lines inone block. Convert tohex, 38 6502 screen flash This program swaps the two blocks, byte by byte (i.e. character by character), starting with the last byte in each block. It loads these bytes into the registers, then stores thebyte from block a in the screen location for block b and vice versa. Then the programis repeated to swap the next pair of bytes. ‘po000090000000000N00000000000000 Go9000000000Bea00D09000000000000 Ituses indexed addressing to find the address for each byte. The total number of bytes in one block is loaded into the X register. Then, to store or load a byte, the number in the X register is added to the 6502 screen flash program starting address for each block. The instruction DEX (decrement X) makes the computer subtract 1 from X so that, when the program repeats, the computer fetches the next byte back in the display. See the bottom of the opposite page for how to work out the values ofn, and b. Then subtract | froma and b so that when the computer adds X it gets the last address ineach block, rather than the first address of the next line. (Make sure n, a and bare inhex.) Mnemonics [Hex codes | Meaning LOX #n [Aan Load X with the number of bytes in one block. ‘| UDA addressa [BDaddress al Put contents of location with address aX into accumulator. TAY [As Transfer contents of accumulator to register Y. __] LDAaddressb,X [BD address b| Put contents of location with address b +X into accumulator. [STAaddressa,X __| 9D addressa| Store contents of accumulator at address a+ X. TYA STAaddressb,X __ 9D address b DEX TCA BNE o instruction two | D0 EF 8 Transfer contents of ¥ register back to accumulator. Store contents of accumulator at address b+ X. Decrement X. Zeroflag is setto lwhenX=0. Branch back &EF locations if X is not equal 00. EF is the RTS. Return hex for two's complement of 17 (see page 37). Loading and running the program ‘The best way to runthis programis asa machine code subroutine in the hex loader. To do this, follow these steps: 1. Type inthe hex loader and put the hex codes for your computer's microprocessor in line 160. 2, Atline 180 you need two loops to poke the characters for the display intothe screen memory. For example, here are the lines for two rows of *s (code 42) followed by two rows of 0s (code 48), fora ‘computer witha 40 column screen. 180 FOR J=0 TO 79 190 POKE first screen address + 3.42 200 NEXT J 210 FOR J=80 TO 159 220 POKE first screen address + J,48 230 NEXT J for the 280 or 6502 3, Next, add the following lines to theend ofthe program: 240 CALL address where machine Eade is stored 250 FOR K=1 TO 500 260 NEXT K Change figure 800indelay 270 GOTO 240 looptosuit your computer. 4. Now type RUN to runthe program. The hex loader pokes the hex codes intothe memory, then pokes the display codes into the screen memory. Line 240 makes} goto the location where the machine ¢: program is stored and carry out the instructions. By itself, the machine code program only swaps the display once, so line 270 makes it call the programagain. and again tomake a flashing effect. You need the delay loop because the machine code is so fast. 39 Going further If you want to find out more about machine code the best way is to try writingyour own short programs and to test and study programs written by other people. One good way to use machine code is asa short subroutine to carry outa particular task ina BASIC program. For instance, machine code is particularly suitable for sorting data or filling the screen with araphics because itis faster and takes less memory space than BASIC. You can find subroutines for doing things hke this inmagazi Ifthe subroutines are written specially for your computer you can run themwithout alteration. Ifthey are wnitten for another make of computer which use: thesame microprocessor you will need to change any addresses in the program for addresses in the area in your computer's memory that you have chosen tostore machine code. Machine code subroutines Here are the steps youneed to follow touse amachine code subroutine ina BASIC program 1, Make room in the memory for the machine code by lowering the top ofuser RAM (see pages 20-22). 2. Put the codes for the machine code subroutine into line 160 of the hex loader program on page 24. (Make sure there isa return instruction at the end of the machine code program.) Add lines to poke in any data bytes if necessary, then type in and run the hex loader. 3. Number your BASIC program using line numbers starting after those used in the hex loader. At the point where you wantthe computer to carry out the machine code, put your computer's command for runninga machine code programas a lin BASIC program =~ This tells the computer togoto location 16002 and carry out the instructions there, 4, Type the BASIC program into your computer and then type RUN. The computer will carry out the BASIC instructions and when it reaches the line telling it to run the machine code program it will goto the address where the machine code is stored and carry out the instructions. The return instruction at the endof the machine code will send the computer back to the next line in the BASIC program. Using an assembler Anassembler (a program which enables you totype in a machine code programin mnemonics) makes machine code programming much easier. You can buy an assembler on cassette for most home computers and some, such as the BBC, have a built-in assembler. ‘With anasseribler you cantype in comments alongside the mnemonics to remind you what each line does. The assembler will then display the program. onthe screen in hex and mnemonics, with the addresses where the instructions are stored and the comments The assembler will automatically reverse the pairs of digits in addresses and work out the address or displacement fora jump. Some assemblers allow youto use symbolic names for data, like variables in BASIC. A good assembler also has a debugger to find mistakes and an editor to help you correct them. Suggested books ‘There are lots of books on machine code specially written for one particular make of microcomputer. The best way to choose oneis to read the reviews incomputer magazines. You may also find the following books useful: Programming the Z80 and Programming the 6502, both by Rodney Zaks and published by Sybex. These are very detailed guides with complete lists of all the instructions for each microprocessor. They are not easy to read for beginners, but they are useful for reference. VIC 20 Programmer's Reference Guide published by Commodore. 6502 Machine Code for Beginners by A. P. Stephenson, Newnes Microcomputer Books. Decimal/hex conversion charts This chart converts hex numbers from 0 to FF to decimal and vice versa. Hex to decimal To convert a hex number to decimalread Decimal to hex ‘To convert a decimal number to hex, find along the row for the first hex digit in yourhex the decimal number in the chart. Then read. number and down the column forthe second hex digit. The number where the row and column meet is the decimal equivalent for your hex number, e.g. hex Alis decimal 161 back along the row for the first hex digitand up the column for the second hex digit e.g. 184is 9A, ‘Second hex digit eo 1)2]3 a [o9[aleal|c ole o 3] 7] 2] 3) 4] 6 1 sat atest wet ar] 2 25 | 43 [4a] 45 | a6 | a7 3 51] 38 | 60] 61] 62) 63 rat al 75\_76| 77 | 78 | 79 | 5 83 91/92] 93 195 Bel [997 joa 705 | 706 | 707 | Toe | 708 | Ti Sra] 115 | ¥20_| 121 | 722 | 123| 124 | 125 127 | sts [30-131 736-137 [138 | 138.[ 140] 141 143 % 9 | 14a 148 [Fae | tar [ise } 163 | 15a | 195] 156 | 157 | 158 | 159 aio [iar | 162 | 163 68 [36a [70 Lin | 72 1173 | 175 B [ie [177 ) 178 | 179 Ted_| 185 | 186-187] 186 | 189 | 190 {191 [-¢ [1921193 | 194 [195 200 | 201 | 202 | 203 | 204 | 205 | [207 O-| aoe [209 [210 211 | 216 | 217 | 21@ | 219 | 220 | 221 | 222 | 203 E | 224 [228 | 226 | 227 | 228 | 273 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 F-[2a0-] 241 [242 [243 | 24 | 245 | 246 | 2a7 | 248} 2a9 | 20 | 261 | 282 | 753 | 254 | 255 Converting addresses ‘Touse the chart to convert hexaddresses, lookup the decimal equivalent for the first pair of digits in the address. This isthe page number, Then look up the decimal equivalent for the second pair of digitsto find the position on the page. Multiply the page number by 256 and add the position onthe page. Two's complement conversion chart ‘This chart aives the two'scomplementin hex of decimal numbers from —} 10 ~ 128. To convert a number totwo's complement, find the number in the chart, thenread along the row for the first hex digit and up the column for the second digit. ‘Second hex digit F p[clela 6 [5s |]4a,]3j]2\1 F 3) 4] s| 6 Li} 2) 3) a) rey af ia | 20} a1] 22 26 | 29 [30] 31 BD] 35) 36) 37 | 38 a2 as] a8| a7 | a8) Bic so] st {52 [sa] 54 58 er] 62] 63 | 64 eB 66 67 68 69 70 74 77 78 79 80 fra @2| 83[ 84] 85| 86 86 | 30 | 2{ 93] 94[ 9s] 96 “io [38] 99 | 100 | 101] 102 | 103 | 104] 106 | 106 | 107 | 108] 109) 170] 111 | 112 a [ris tia bans | ret tiv} ate [ais } 120] tat T 20 t v23 | 12a] 195 | 126 127 | 128 Doing conversions onacalculator To convert the remainder to awhole When you do conversions on a calculator number you subtract the number before the the calculator displaysthe remainderasa decimal point, then multiply by the number decimal number, For example, if youare you divided by. converting decimal 134 to hex you divide by oe _ I6then convert the answer andremainder_ °379—8= 0.375 16=6 a tohex digits. A calculator would give you the answer as 8.375. So 134 + 16 =8 remainder 6therefore decimal 134 is 86 in hex 42 Z80 mnemonics and hex codes The mnemonics and hex codes for the instruc the next few pages. The term “implicit addre: ‘ons covered in this book are givenon ing” used in Se lists is just thename for instructions where no operand need he specified in the hex code. There area few other instru Ctions not listed here and if you want to ge further with machine code you will need a complete list of the Z30 instruction set (see page 40). The following abbreviations are used in these list n =number nn = two byte number x =register x rr = register pair =address c d =displacement = condition — ADCA,n Add with carry.a number, n, othe accumulator. CALLx Gotosubroutine starting at address x {immediate addressing.) DECr Decrement register r (Implicit addressing.) ADDA,n Addanumber,n,to the accumulator. (Immediate addressing.) ADD,n Cé.n ADD A,r Addregisterrtothe accumulator. (Implicit addressing.) ADDAA 87 | AOBA 80 ADDA,C 81 ADDAD 82 ADD AE 83 [ADD AA 84 _| ADDAL 85 ADDHL yr Add the contents of register pair rr toHL. (Implicit addressing.) | ADDHLBC 09 __ ADD HL,OE 19 ADD HL,HL 23 (Immediate addressing. ) if _| DECA 30 ADCA,n CE,n CALL x cDx _DECB 0 4 ADC A,x Addwith cary, CALLex Gotosubroutine DEC 0D register rto the accumulator. starting at address x |_DECD 15 __ dmplicit addressing.) depending on conditionc. DECE 410 - cmay be Z (equal); NZ(not DECH 25 ADCAA _8F equal); (carry); NC (no DECL 3D ADCA,.B 88 carry); PE (parity even); PO ADCA.C 89] (Panty odd); M (minus) or P DEC rr Decrement register ADCA.D. BA, (plus). (Immediate [parrrr. (Implicit addressing.) _| ADCA.E 8B. addressing.) [pec ac 0B | ADCAH BC CALLZ.x DEC DE 16 ADCAL 80 CALL NZ.x CALLC,x ape Lex Add with carry, [—CALLNC.x the contents of register pari || —CAact PE toHL. (Implicit addi > |Pcanteos DEC (HL) Decrement ° (implicit addressing CALL PO,x contents of address held in HL. ADCHLBC ED4A CALLM.x (ndirect addressing ) ADCHL.DE _EDSA CALLP.« aos —_ 35 ADCHLHL _ED6A DEC HL) CCF Complement carry flag. Gmplicit addressing.) CCF 3aF Pn Compare contents of accumulator with data n. Immediate addressing.) CPn FEn Pr Compare contentsof register with the accumulator. (Implicit addressing.) INCr Increment register r (implicit addressing.) INCA INCrr Increment register pair rr, (Implicit addressing.) CP(HL) Compare contents of accumulator with contents of address held in HL. (Indirect addressing.) CP (HL) BE INCBC 03 INC DE 13 NCHL 23 INC (HL) Increment contents ofaddress held in HL. (Indirect addressing.) INC (HL JPx Jump to address x. (immediate addressing.) JPx C3x 34 JP(rr) Jump toaddress held ial register pair rr, (Implicit addressing.) LDA, (x) Load accumulator with contents of address x. (Absolute addressing.) LDE,r Load register E with the contents of register r. (Implicit addressing.) equal); C (carry); NC fro, carry); PE (parity even); PO (parity odd); M (minus) or P (plus). (Immediate addressing.) JRd Jumptelative. Jump bytes the displacement) (Relative addressing.) __JRé 18d JRed Jump relative, Jump d bytes (the displacement) depending on condition c. may be NZ (not equal);Z (equal); NC (no carry) or C (carry), (Relative addressing.) | JP (HL) Eg LOA, (x) 3A, bx) LDEA SF | JP(X) DDES LOEB 58 UPAIY) DES LD 1, (x) Load register pair rr LDEC 59 with contents of addresses x LDE.D 5A JPex Jumpto address x and x+ 1. (Absolute ‘LOEE SB. depending on condition c. addressing.) “DEH «SC. emay be Z (equal): NZ (not LOBC Ix) EDaB,(x)_|{ LOEL so LDDE, (x) _EDSB, (x) UDAL x) 2A) LDA,x Load the accumulator with contents of register r. (implicit addressing) _LDAA 7F DAB 78 Ac 79 LOA,D 78 LDAE 23 | LDH,x Load register H with the contents of register r (implicit addressing.) 67 LDL, Load regisier Lwiththe contents of register r. (Implicit addressing.) LDC,r Loadregister C with the contents of register. LDB,r Load register B with LOLA 6F the contents of register r LOL. 68 (mplicit addressing.) LOLc 69 LDBA 4? —__5A | tbB.8— aC pa) LADLE OB. 4 LDB,C eH 6c LOBD - LDL,L 60 LOBE || ud, @2) Load register r with LOBH —__ | | contents of address held in LDBL ~ | | register pair rz. (Indirect addressing.) LDA(BC) 0A LDAIDE) iA Gephichaddressing) IT Lp AHL) 7 | LD« oe [| LD BAHL) 46 4 LDr,n Load register r with LOC,B 43 LOCAHL) 4E datan.(Immediate tocc 49 | | _LD DAHL) _56 7 addressing.) | LDC.O aA —] [-LDEMHL) SE LDAn LOGIE AB LDH(HL) 66 LOB,n LDC,H 4c LD LHL) 6E [DCnees Loc 40 LD (x),A Store the contents of | _LDD,n | . the accumulator in address x. LOEn LD D,r Load register D with (Absolute addressing.) the contents of register r. (implicit addressing.) LO(x).A, 32x 57 LD 00,rF Store the contents of LD nn Load register pairtr gq] | register pair rr at addresses x with two byte number nn. S17 atx 1 (Absolute (Immediate addressing.) eee addressing.) | LDBC,nn __O1.nn 53 LO(x), BC ED43,x LODE,nn inn 54 LO(x)DE -ED53.x LOHL,nn 21,.nn 55 LD (x),HL 22, 43, LD (mx Storethecontentsof || RETC 08. SBC A,(HL) Subtract with register ratthe address held in | | RETNC Do carry the contents of address register pair 1x. (Indirect RETPE E8 held in register pair HL, from addressing.) RETPO £0 the accumulator. (Indirect LO(BC),A 02 RETM. _F8 addressing). _| LDIDE,A 12 RETP FO SBCA(HL) _9E LD(HLLA 77 = TOL} 70 |] SBCA,n Subtract with carry || SOF Set carry lag (Implic LOHE.C 71 |) Aatanfromtheaccumulator. || #dézessing) | [ToD 72 | Limmediate addressina.) SCF 37 LD(HL).E 73 SBC An DE,n SUBn Subtract datan fromthe LD(HL).H 74 JJ} accumulator. (Immediate LD(HL).L 75 SBC A,r Subtractwith carry || addressing.) LD(m),n Store datanat eer deal SUB.n 06.0 address held in register pair. | addressing.) SUBr Subtract contents of (Immediate/indirect : | register fromthe addressing.) || SBCA _9F__]| accumulator. (Immediate LO{HL)n 36 ee 28 addressing.) Ai 99 RET Return from subroutine SCAB oA 7 _| (indirect addressing.) E98. | 9 RET ca A 9c a RETe Retumnfrom subroutine ||_ SBC AL 8D | depending on condition. ; 34 Sean be Z (equal): NZ (not SBC Hire Subtract withearry |} SUR —__98_) contents of register pair rrfrom yal); C1 ); NC (no. See nou oven) register pair AL. (Implicit SUB (HL) Subtract the carry); PE (parity even); PO (parity odd); P (plus); M addressing.) contents of address held in HL. (minus). (Indirect addressing. } SI — ~~] | from the accumulator. (Indirect SBCHLBC _ED42 om RETZ ca SBCHL,DE ED52 addressing.) L RET NZ co ‘SBC HL,HL ED62 SUB (HL) 96 Puzzle answers Tip:an easy way t0Work out the two's ‘complement of a numbe: subtractit SA?indecimalis 167. SISinkexis@201. << ffomZ6e, then convert theancwer tohex Page 26 E.g. 256--6=250 whichis FA inhe 1. 25+73 (25is &19 and 73is &49) s wae 780 502 _ Meani Mnemonics Hexcodes | Mnemonics | Hex codes caning LDA, &19 3E,19 LDA #619 4919 Puldl@inaceumulator ADD A, &49 C649" ADC #&49 69.49 ‘Add &49 toaccumulator, Store contentsof LD (address), A | 32,addxess | STAaddress | 8Daddress | accumulaoratacenain RET [co RTS 60 Retr 2.64-+12+14 (64is 40, 12s &0C and 14 is &0E) Z80 6502, Meani Mnemonics Hexcodes | Mnemonics | Hexcodes | “1°@™79 LDA,&40_____ | 3E,40 LDA #&40___ | A940 Pui &d0 inaccumulator | ADD A, &0C C8,0C ADC #&0C | 680C ‘Add 80 ro accumulator ADD A, 0E C60E ADC#Q0E | 690E ‘Add 40E to accumulator. Store contentsof LD(address),A | zaddress | STA address | aDaddress | seciinslaterate cenain RET co RTS 60. Rew Puzzle answers continued on page 48. 6502 mnemonics and hex codes This chart shows the mnemonics and hex codes for all the instructions (plusa few more) covered in this book, The mnemonic instructions are given down the leftand the hex codes for each instruction in the different addressing modes are shown across the Chart. Zero page addressing is just like absolute addressing, ie. the operand is the address where the data is stored, but the address must be inpage zero (1.e. locations 0-258) of the memory (see page 10). Implied addressing is just the term used to describe instructions where no operand need be specified, e.g. CLC. There are a number of other instructions not given here, and if you want to gofurther with machine code you will need to geta complete hist of the 6502 instruction set. Addressing mode Relative Data Any _|Address Address Address None | Displace- adaress |inpage | +X HY ment zero register register Operandis ADC Addwithcary,ie.addabyte,plusthe | 69 | 6D 6 | 70 79 cary flag, to the accumulator. ‘BCC Erarchif carry clear. BCS Branchif carry set. BEQ Branchif equal. FO Note thatnotall the instructions can ) 90 be usedin all the addressing modes. {80 BMI Branch if minus. 30, BNE. Branch if not equal DO 'BPL_Branchil pius. 10 BVC Branchif overflow clear 50, BVS Branchif overfow set. ~ I 70 CLC Clear carry flag. I {38 co CMP Compare with the accumulator, co} cs [0b be GPX Compare withregister X £0 [6C | Ed ‘CPY Compare withregister Y. co_{cc_ | _ca DEC Decrement (subtract | from) memory cE ce | DE location. | DEX Decrement (subtract | from) X register CA DEY Decrement (subtract | from) ¥ reaister, | I 88. INC increment add I to) memory location. EE 6 | fe INX Increment (add Ito) X register. eB INY Increment add 1 10) ¥ register i ce IMP_Junp toaddress specihed mn oporand_| a JSR jump tosubroutine staring at address 20 specified inoperand, [LDA Load accumulator, AS_| AD As_ | BD i} LDX Load X register. Az_| AE AG BE LDY Load ¥ reaister. ‘AO_| AC Aa_|_ BC RTS _Retum from subroutine. 0 SBC Subtract with carry. Subtract fromthe FS | ED a) 79 accumulator and borrow fromthe carry flag._| SEC Set carry flag — a /STA_Store accumulator at a certain address, 80 3 | 90 39 STX Store X register ata certainaddress, 8 86 STY Store ¥ register at acertainaddress aC, 84 TAX. Transfer accumulator to X register. AA [TAY Transfer accumulator to Y register. AB XA Transfer X register toaccumulator. BA [TYA Transfer ¥ register to accurulator. 98 45 Machine code words #Hashsign. Thisis the sign used on some computersto indicate hex numbers. For the 6502 microprocessor it is used to indicate a piece of data. & Ampersand sign. Thisis another sign used to indicate hex numbers, Absolute address. The actual address of a piece of data. Absolute addressing. An addressing mode in which the instruction contains the address of the data, Also called extended ordirect addressing. Accumulator. The register where bytes of information on which arithmetical or logical operations are to be carried out, are held Address. Anumberusedto identify a location in the computer's memory. Addressing modes. The vanous ways in which you can tell the computer where to find the data to work on ina machine code program. Arithmetic logic unit (ALU). The area inside the CPU where arithmetical and logical operations are carried out Assembler. A program which converts instructions written in assembly language mnemonics into the computer's own code. Assembly language. A methodof programming the computer using letter codes, called mnemonics, to represent machine code instructions. Binary. Anumber system with two digits, 0 and | and in which each digit ina number hastwice the value of the digit on its right. Bit. A single unit of computer code, i.e. a1 or 0 representing a pulse or no-pulse signal. Buffer. A temporary storage area inthe computer's memory where data is held on its way to or from its final destination. Branch. Aninstruction telling the computer to jump to another line ina program, Byte. A group of eight pulse and no-pulse signals (or “bits") which represents a piece of information in computer code. Carry flag. A bitin the flags register which isset to | when the result of an addition will not fit into eight bits Clear. To make abit, e.g. one of the bitsin the flags register, zero. Complement. Also called “flipping the bits" this is the process of changing all the 46 Osinabyteto | andall the 1sto0, Conditional branch. An instruction which tells the computer to jump to another line in the program depending on the result of a test Direct addressing. See absolute addressing. Disassembler. A program which can display the contents of a series of memory locations on the screen in assembly language. You can buy a disassembler on cassette and itis useful for debugging machine code programs and for examining the programs in your computer's ROM. Displacement. A number used ina jump or branch instruction to tell the computer how many locations to jump to find the next instruction. Also called an offset. Flag. Abitin the flags register whichis used to indicate a certain condition, e.g. the presence of a negative number, or ofa carry over inan addition. Hexadecimal, or hex. A numbersystem whichuses 16 digits (the numbers 0-9and letters A-F). Each digit in a hex number has 16 times the value of the digit on its right. Hexloader. ABASIC programwhich converts the hex codes of amachine code program into decimal numbers and pokes them into the computer's memory. Highorderbyte. The first two digits ina hex address which represent the number of the page in the memory where the address is, Also, the two digits which show how many 256s there are ina number larger than 258. HIMEM. The highest address in user RAM. Immediate addressing. Anaddressing mode in which the data for an instruction is included in the instruction. Implicit addressing. An addressing mode inwhich the operand is understood and need not be specified. Implied addressing. Same as implicit, see above. Indexed addressing. An addressing mode in which the contents of anindex register are added to the address given in the instruction to work out the actual address of the data. Index registers. The registers used in indexed addressing and also, in the 6502, as, general purpose registers. Indirect addressing. An addressing mode in which the operand isused asa pointer to the data. The operand may be an address or, inthe 280, a pair orregisters, andit holds the address of the data Instruction. An operation to be carried out by the central processing unit Interpreter. A program whichtranslates instructions in BASIC (or other high level language) into the computer's own code. Instruction set. Allthe operations which canbe carried out by a particular microprocessor. Jump. An instruction which tells the computer to go to another line in the ‘program. LIFO. This stands for “last in/first out” and describes the method used by the computer to store information in the stack. Low order byte. The two hex digits inan address which give the position of that address within a page of memory. Also, the two hex digits which show the number of units ina number larger than 255 Microprocessor. The chip which contains the computer's CPU and which carries out program instcuctions and controls all the other activities inside the computer Mnemonic. A letter code used in assembly language to represent an instruction in the computer's own code. The word mnemonic (pronounced nemonic) means “to aid the memory” and assembly language mnemonics sound like the instructions they represent. Object code. A program which hasbeen translated into machine code from assembly language or another high level language. Offset. See displacement. Opcode. The part of an instruction which tellsa computer what todo. Operand. The part of an instruction which tells the computer where to find the datato work on. Operating system. A group of programs written in machine code and stored in the computer's ROM, which tell it how to carry outall the tasks ithas todo. Page. A subdivision of memory. On most home computers a page is 256 locations. Pointer. A memory location (or pair of registers) which contains the address ofa piece of data. Pop. Toremove anitem stored in the stack. Processor status register. Thisis the 6502 name for the flags register (the register where each bit is used'o record a certain condition inside the computer), Program counter. The register which contains the address of the next instruction tobe fetched from the memory. Pull. Sameas pop, i.e. to remove anitem from the stack Push. To place an item inthe stack. RAMTOP, The highest address in user RAM. Registers. The places inthe CPU where bytes of instructions, data and addresses are held while the computer works on them. Relative addressing. An addressing mode in which the computer works out the address of the next instruction by addinga number called the displacement or offset, tothe address in the program counter. Screen memory. The locationsin RAM which are used to hold information to be displayed on the screen Sign flag. The bit inthe flags register whichis used to indicate negative and Positive numbers. Source code. A program writtenin assembly language, or other highlevel language such as BASIC. Stack. Anarea of the memory used by the computer for temporary storage and where the last item stored is always he first tobe retrieved. Stack pointer. A register in the CPU which contains the address of the last item inthe stack Systems variables. Memory locations in RAM which hold information about the current state of the computer. Topofmemory. The highest address in userRAM. Two'scomplement. A system ofnotation used to represent negative numbers. To find thetwo’s complement of a number you complement (make all the 1sinto 0s and all the 0s into 1s) the binary for that number and thenadd 1 User RAM, The part of RAMwhere BASIC programsare stored, Zeroflag. The bitin the flagsregister which indicates when the result of an operation is 0 and is also used to show when twobytes are equal. Zero page. The first 256 locations inthe memory, Zero page addressing. Used only onthe 6802, this is an addressing mode in which the operand is an address in page zeroof the memory (i.e. from 0-255) 47 Puzzle answers continued Decimal Hex Page 28 High order] Low order | High order | Low order 00011010 is 26 decimal 30F T SL kr es 11111011 is 251 decimal 21214 82 222 882 &DE 10101010is 170 decimal 759 2 247 ‘&02 SFT 1023 3 255 &O3 SF Page 31 ‘To adapt the program on page 27 for given below. To answers greater than 255 you need todelete command: see the result you use this the return instruction and add the lines PRINT PEEK(address 3) + PEEK(address4)*256 280 6502 Meanin ‘Mnemonics Hex codes | Mnemonics | Hex codes caning LDA, &00 3E,00 LDA #800 900 PurOimaccumulator [ADC A, &00 CE.00 ADC #&00 6900 Adatwath carry. Oto LD(address 4), | 32,address4 | STAaddress4 | gDaddress4 | Sorecomeneot RET ce RTS 60_ Return. Page 37 Hex for the two’s complement of 12is &F4; 18 is &EE and 91s @F7. Index ‘& ampersand sign, 8, 12, 16, 18, 46 dump, 19 13, 20-21 # hash sign, 12, 16, 18, 46 loader, 5, 25, 24, 25, 46 RAMTOP 8, 20,21,47 absolute addressing, 18, 22 46 number system, 5,8, 11.45 lowering, 20-22 accumulatoz, 1-15, 17,30, 32, 46 address, 8-9. 11, 19,46 converting to hex or decimal, 11 inmachine code, 18-19 addressing modes, 27,46 ALU (anithmetic/logic unit), 13, 14, 46 ASCII code, 13, 24,32 assembler, 5.16, 40, 46 assembly language, 5, 17, 19. 46 high order byte, 19, 28.30, 31,46 HIMEM, 8, 20, 21, 46 immediate addressing, 18, 27,33, 46 implicit addressing, 46 implied addressing, 46 inerement, 33,34, 38 Indexed addressing, 34, 39, 46 index registers. 14-15, 45 indirect addressing (280), 33,98, 46 ‘Atari, 3,24 Instruction, 4,5, 13-14, 16, 47 BASIC, 4. 12,20, 40 instruction set, 16, 47 big numbers, 28, 30.92 interpreter, 4,8, 20, 47 binary, jumps, 33, 35,47 code, 4,5, 16 LIFO, 10.47 numbers, 4, 19,28. 46 tohex conversion, 37 it, 4,46 branch, 34,35, 46 butters, 10.46 byte. 4, 13, 19,20, 45 carry fiag, 14.18, 17,29, 30,31, 36, 46 carrying over numbers in addition, 28, 30,3 character codes, 13,32 clear, to, 29, 48 Commodore 64,3, 7 comparing, 32 complement, 46 conditional branches, 35, 36-92, 46 locations, memory, 8-8, 10, 1, 12-13 lowering RAMTOB, 21 Tow order byte, 19, 28,30-31, 47 machine code, checklist, 26 Jength of program, 20 subroutines, 39, 40 where to store in memory, 20-22 memory, 8-8, 10, 12-13, memory map, 8 microprocessor, 7, 16,47 mnemonics, §, 16-17,47 object code. 18, 47 offser, 96-37, 47 opcode, 18, 18, 19, 47, control unit, 19, 44 operand, 16, 18, 27,47 (CPU (central processing unit), 1, ‘operating system, 8, 10, 1,13,20,47 14-15, 16, 19 Oric micro, 3,7, 21 crash, 20 overflow bit, 36 databytes, 23, 28 decimal numbers, age (of memory), 10, 11, 16,21, 47 Mal parlty/overflow bit, 36 decrement, 36,38 PEEK, 12-19, 21,26. 31 direct addressing, 27,46 pointer, 33.47 disassembler, 46 POKE, (2-13.23 displacement, 96-37, 46 display file, 8 extended addressing, 27 flags register, 14-15, 17,29, 38, hex, codes. 16, 18, 19 converting to decimal, 11,41 pop, 35,47 Postion on page (of address) 1,18 processor status register. 15,29, 47 (see also flags register) program counter, 14-15, 35, 47 RAM (random access memory), 6, 12, 48 registers, 13-14, 27,30,31,47 relative addressing, 36, 47 REM statement, storing machine code in, 22 reserved for use of the operating system, 8, 10 return instruction, 23,35 ROM (read only memory), 6, 12, 13 runainga machine code program, 25 screen memory, 8, 13,47 set, 10, 23, sign flag, 14,36, 47 source code, 18, 47 Spectrum, 13,24, 32 stack, 10, 14, 15, 20,35, 47 stack pointer, 14-15, 47 subroutines, 35 systems variables, 10,20. 21.47 Timex 1000, 8,13, 22, 24 ‘Timex 2000, 13, 24,32 top of memory, 20, 21, 47 two'scomplement, 37.41.47 user RAM. 8,20, 47 VIC 20, 7, 13:22 zero llag, 32, 33, 94, 36, 47 zeropage, 10, 45,47 zero page addressing, 48, 47 2X81,9, 13, 22, 24 Hex loader conversions Change these lines for the 2X81 (Timex. 1000 40 INPUT He 70 LET (CODE CHS) 89 Delete 99 LET Y=cOpE (Ha (2 TO 1-26 LET Y=x+¥ Delete 155 Delete 160 Delete Change this line for Atari computers 90 LET Yaase (Abe 2arets row 110 Usborne Computer Books are colourful, straightforward and easy-to: understand guides to the worid of home computing for beginners of allages. Usborne Guide to Computers A colourful introduction to the word of computers. “Without question the best general introduction to computing / have ever seen. Personal Computer World Understanding the Micro _A beginner's guide to microcomputers, how touse them and how they work. “This introduction to the subject seems to get everything right.’ Guardian Computer Programming Asimple introduction to BASIC for absolute beginners. “... /ucid and entertaining...“ Guardian Computer and Video Games Al about electronic games and how they work, with expert’s tips on howto win. “The ideal book to convert the arcade games freak to real computing.” Computing Today Computer Spacegames, Computer Battlegames Listings to run on the 2X81 Spectrum, BBC, TRS-80, Apple, VIC 20 and PET. “Highly recommended to anyone of any age. “Computing Today Practical Things to do with a Microcomputer Lots of programs to run anda robot to build which will work with most micros. Computer Jargon An iiustrated guide to all the jargon Computer Graphics Superbly illustrated introduction to computer grapnics with programs anda graphics conversion chart for most micros. Write Your Own Adventure Programs Step-by-step guide to writing adventure games programs, with lots of expert's tips. Machine Code for Beginners A eaily simple introduction to machine code for the Z80 and 6502. Better BASIC A beginner's guide to writing programs in BASIC. Inside the Chip Asimple and colourful account of how the chip works and what itcando. ede publishing 8141 E. 44th St. Tulso, OK 74145 ISBN 0-88110-170-2

You might also like