100% found this document useful (1 vote)
268 views

Machine Code For Beginners

computers

Uploaded by

Gabriela Zilli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
268 views

Machine Code For Beginners

computers

Uploaded by

Gabriela Zilli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 51
USBORNE INTRODUCTION TO-@ MAC = y ECO » RS E t N | N y ‘ Ni | sEGI Dy L) | R FO Usborne Computer Books USBORNE INTRODUCTION TO MiiGaliNe Cire Illustrated by Naomi Reed and Graham Round Designed by Graham Round and Lynne Norman 6502 consultants: A. P. Stephenson and Chris Oxlade 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 1983 by Usborne Publishing Lid, 20 Garrick Street, London WC2E 9B], England. Usborne Publishing Allrights reserved. No part of this publication may be reproduced, stored in a retrieval system or tansmitted in any form or by any means, electronic, mechanical, photocopying. recording or otherwise, without the prior permission of the publisher. ‘The name Usborne and the device — are Trade Marks of Usborne Publishing Lid 2 Printed in Spain by Printer Industria Grafica, 5. A. - Depdsito Legal B. 33.755/1983, About this book This book isa simple, step-by-step guide to learning to program in machine code. Machine code isthe code in which the computer does allits 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 book takes youin very easy stages through the basic principles of machine code. It shows you how to write simple machine code programs, for example, to add twonumbersor flasha message on the screen, and how toload and runa machine code program on your computer. The book is specially written for computers with a Z80 or 6502 microprocessor,” The microprocessor isthe chip which contains the computer's central processing unit and computers with different microprocessors understand different machine code. All computers with the same type of microprocessor, though, use the same machine code. Machine code is difficult and very laborious, with lots of rules to obey and small details to remember. Don't worry if you find it very hard at first. Itseems confusing as you cannot readand understand a program in machine code ~it's just a string of letters and numbers. Bugs are very difficult to spot, too,and have disastrous results if you missthem. When youare working in machine code you have to be very careful and methodical and check everythingtwo orthree times. Unless you are really dedicated there isno point in writing long programsin machine code-some things canbe done just as well in BASIC. Forcertain tasks, though, such as speeding up the action in games programs or creating fantastic screen effects, you need touse machine code. This book shows you howto 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 words to explain all the jargon. There are also lots of puzzles and ideas for short programs to write, withanswerson page 44. “The Spectrum and 2X81 (Timex 2000 and 1000) use the 280 microprocessor and the VIG 20, the BBC, the Atari computers and the Oric use the 6502. The Commodore 64 uses the 6510 and understands 6502 machine code. Whatis machine code? ae Machine code is the code in whichthe Inmachine code, each instruction and computer does all its work. When yougive __piece of informationis represented bya a computer a program in BASIC, allthe binary number. Binary is anumber system instructions and data are translated into which uses only two digits, land 0. Youcan machine code inside the computer. write any number in binary using Isand 0s.* Inside the computer, the binary numbers The bits flow through the computer in are represented by pulses of electricity, groups of eight and each group is calleda witha pulse foralandnopulsefora0.The “byte”. Each byte of pulses and no-pulses pulsesand no-pulsesare called “bits",short represents the binary number for one for binary digits. instruction or piece of information in machine code. Each task the computer cancarry out,such —_understands. as adding two numbers or clearing the The term machine code is also used to screen, involves a sequence of several refer to programs written ina form whichis instructions in machine code. When you much closer to the computer's code than give the computer a BASIC command, a BASICis. Inamachine code program you special program called the “interpreter” have to give the computer all the separate translates yourcommandintothe machine _ instructions itneedsto carry outa task such code instructions the computer as clearing the screen. *Youcan find out more about binary on page 28. Programming in machine code There are several different ways of writing machine code programs. You could write allthe 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, hex ismuch easier to work with than binary. Machine code programs can also be written ina code called “assembly language”.In assembly language each instruction to the computer is represented by a“mnemonic’ (pronounced nemonic) ~a short word which sounds like the instruction itrepresents. 3Eisthe hex code for an instruction, Thisis a program for computers with a 280 microprocessor. You can find out how the: program works laterin the book. Thisis part of amachine code programin hex. The hex number system has sixteen digits and uses the symbols 0-9 and A-Fto represent the numbers 0 to 18. (You can find out more about hex later inthe book.) The hex number at the beginning of each line of the programis an instruction (e.g. 3E). Itis the hex equivalent of the binary code for that instruction, Togive acomputera program inassembly language you needa 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 anassembleron cassette and load it into the computer's memory. Alternatively you can writea machine code program using the LD A isthemnemonic for an instruction. program to add 2+4, 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 the left. For example, the mnemonic LD A (pronounced “load A”) means the sameas the hex number 3E. In both these programs, eachline 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 you give ‘them to the computer. Some computers will accept hex numbers; with others youhave to give thema short program, calledahex loader", which translates them forthe ‘computer. There is ahex 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 programa computer in machine code you have to tell itexactly what to doat each stage: where to find and store data, how to print onthe screenand soon. (When youare workingin BASIC, special programs inside the computer take care ofall this for you.) Inorder to give the computer the correct machine code instructions, you need a good idea of what is going oninside your computer. The pictures on these two pages show the parts inside a home computer, and what they are for. You can find out more about them on the next few pages. What the chips do This picture shows the work carried outby the different chips inside the computer. Messages flow between the chips in the form of bytes, i.e. groups of eight pulse and no- pulse signals representing data and instructions. The ROM chips ROMstands for “read only memory”. The machine code instructions which tell the computer what to doare stored inthe ROM chips. Itis called 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 into computer code) is in the ROME | Inside a computer etc Inside the keyboard of amicrocomputer there isa printed circuit board. This has metal tracks printed oni, along which electric currents can flow. Attachedto the printed circuit board there area number of chips. Bytes of computer code flow between the chipsalongthe tracks ofthe printed circuit board. There are three J separate systems of tracks for carrying bytes' for doing different jobs. Each system of tracks is called a “bus”. memory”. This is where 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 the information stored in RAM is wiped out Enlarged view of circuits inside ch The proper name fora chip isan ‘integrated circuit” and inside each chip through the circuits in the chips. Th there are microscopic electrical circuits. are different chips for carrying out All the 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 pi Glock This is a quant 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 makes of microprocessor chip and all home computers use one or other ofthem, The most common makesare the 80, found in Sinclair (Timex) computers, and the 6502, used inthe Orie, the BBC micro, the VIC 20 and many others. Other examples of microprocessors are the 6809 used in the Dragon computer and the 9900 inthe TI-99/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 280A isa faster version ofthe Z80 and the 6502A and 6510 (used inthe Commodore 64) aré 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 Z80 or 6502 machine code. 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 GPU what to do is inthe ROM. The computer’s memory The easiest way to think of the computer's memory is.as lots oflittle boxes, eachof which can hold one byte, i.e. one instruction or piece of information inmachine code. Each box in the memory is calleda “location”, and each location hasa number, called its address’, so the computer can find any box in thememory. Different areas of the memory are used for storing information for different tasks anda chart giving the address where each area starts is called a “memorymap”. When youare 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 it the address ofa memory location. You even have to tell it where tostorethe 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 Variable storage | like this, or horizontally. The address at which each she eanae ofthe different areas in the memory starts isgiven alongside the map and it may bea decimal number ora hex number, or both, as here. Inthis book hex numbers are distinguished by a &sign (ampersand) before the number. Your manual may use a different symbol, e.g.$, %, or # Input/output Nae ( Thetoundary > betweenuser 1 a RAM and The highest address in user RAM variable storage is called “RAMTOP’, or on some aodtaan computers, “HIMEM how much spaceis ae - needed for variables. BASIC This area holds the interpreter, the program which converts instructions in BASIC inte the computer's binary code. 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 in machine The memory map includ code. There are programs which tell it both ROM and RAM. The how to do mathematical calculations, Cee nee : BASIC interpreter arei programs to clear the screen, find ROMandthe rest ofthe arandom number, scan the areas on the map are in keyboard and all the other RAM. things the computerhas todointhe course ofits work. 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 youcan have ona microcomputer which uses a Z80 or 6502 microprocessor is 64K (ROM and RAM combined). This is because the biggest number you can make with 16 binary digits is 65535, so thisis the highest possible address. This gives 65536 locations, numbered from 0 to 65535. Each location holdsone byte, 1024 bytes make a kilobyte (K) and 65536 bytes equal 64K (65536 ~ 1024 = 64). Onthe 2X81 (Timex 7000) the boundary between the screeny memory and user RAM changes depending onthe size of the program inuser RAM. UserRAM Thisis where the programs you type inare stored, The data for variables and arrays is stored at the top of user RAM. Reserved for use of the operating system ‘These RAM locations are used by the computer to keep track of everything going on while it carries Ifyou add extra memory out aprogram. For instance, to your computer, the information about the position ofthe addresses of some of the aireertiien teat ecreey Colour, areas may change. There should be information which key isbeing pressed and the aboutthis in your manual. current program line number are all stored inthis area. Itisdividedup into smaller areas for carrying cut different tasks. Some computers have asecond map ofthisarea. You can find out more aboutit overthe page. 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. Sinclair/Timex), the locations used by the operating system are not in one group andare distributed throughout the memory. User-defined graphics Ifyoumake 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 uses these 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 usedin calculations. Systems variables These area 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 iteto be stored must always be the firstto be retrieved. This is called LIFO storage: Jastin, first out. Hex numbers Inamachine code program, m wr peri Below you can find out how to convert decimal numbers to hex, and vice versa [Decimal oli[z[3[4[s[e6l[7[s 10/17 Tahal [Hex ofil2]}3i/4/slel7i/s alelc[o/elr This chart shows the hex digits (0-9and digits, just as you do in the decimal system A-F) and their decimal values. Tomake to write numbers over 9. The value of each numbers over 15(F)youuse two(ormore) _dligit depends onis position in the number. ica 2] ACA ishex)s I Decimal ee for 1226. "1000s | 100s | 10s | 1s ba tetate) Oo Inthe decimal system the first, me onthe Inahexnumberthe first digit on the right right of anumber shows how many Is there also shows the number of 1s but the next are, the second shows the number of 10s, digit shows the number of 16s, and the third the third, the number of 100s (10%), ete. digit shows the number of 256s 16") ‘Can youconvert &A7 to decimal and decimal 513to hex? (Answers page 44.) Decimalto hex To convert a decimal number e.g. 1226,to 1226 = 256 = 4. hex, first you divide by 256to find howmany remainder 202 256s there are in the number. Then you divide the remainder by 16 to find the 202 = 16= 12 number of 16s and the remainder fromthis _ Temainder 10... sum gives the number of Is. Finally, convert the answer to each sumtoa hex digit,” .. 4isd inhex 12is Cinhex ...10 is A in hex 1226 is 4CAin hex Converting hex addresses Inahexaddress, 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. Toconvertahexaddresstodecimal,first | Toconvertadecimaladdresstohexyou convert each pair of digits to adecimal have to divide by 256 to find the memory number, as shown above. Then multiply the page number. The remainder gives the page number by 256 (there are 256 position on the page. Then youconvertthe locationsinapage)andaddthe number for __figuresto hex digits as described above. the position onthe page. nl *See page 41 for how to do this ona calculator. 12 Peeking and poking Two BASIC words, PEEK and POKE,* enable you to look at the bytes storedin. the computer's memory locationsand change them. You use PEEK and POKE with the decimal, or onsome computers, hex, addressofamemory 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 computersand some computers will accept only decimal numbers. Using PEEK Totell the computer tolook ina memory location you use PEEK (or your computer's command) with the address of that location. Tosee the result on the screen, use PRINT PEEK, or store the result in a variable using LET and then print out the variable, as shown above left. Poking ‘The picture above shows you how touse POKE. You can poke anywhere in RAM, but ifyou poke new values into the area reserved for use by the operatingsystem youmay disrupt the workings of the computer. You can restore it to normal by switching off and.on again. Try writinga Thistellsthe computer to put 60 in location 16763. Use PRINT PEEK toseethe result, short programlike the one above topoke several numbers intoa series of locations in user RAM. Youcan peek into any location in your computer's memory, but youcan only poke new bytes into RAM locations because the bytes in ROM cannot be changed, These are the decimal equivalents of bytes of computer code. Try writing a short program using aFOR/ NEXT loop, like the one in the centre above, to print out the bytes froma series of locations. Look at your computer's memory map and experiment with addresses in different parts of the memory. This puts.a number, N, into location A. The numbers you poke must be between Oand 285, the highest number than canbe represented with eight binary digits (one byte of computer code). “Some computers use different commands, e.g. the BBC usesa? mark. Check your manual. What the numbers mean When youtell the computer to print the contents of amemory location on the screen, the result is always a decimal number from 0 to 255. This is because each memory location can hold one byte, andthe highest value that can be represented with eight binary digits is 255. There are only 256 (Oto 255) possible different bytes of computer code and each byte canhave 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, for a letter on the keyboard, or for partof the address of another memory location (each address consists of two bytes). Use anaddress in your computer's Type inthe address for your computer's operating system Look in your manual to find the addressin ROM of your computer's operating system and then try this program. The numbers which appear onthe screenare the decimal equivalents of bytes of machine code from one of the programs in the operating system. This isthe ASCli code’ forZ. screen memory, Now find the screen memory for your computer, then try poking numbers into screen memory locations. You donot need touse PRINT PEEK because bytes stored in the screen memory are automatically displayed on the screen. This time the computer interprets the number as the code for acharacter.* Put anaddressin’ 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-255 are for special keys such as SPACE and DELETE, for printing the alphabet in inverse or flashing characters, and for graphics characters, Most computers use the ASCII code (pronounced “askey”), to decide which numbers represent which characters, but some, suchas the 2X81 (Timex 1000)use different numbers. The VIC 20 hasa special set of numbers, called screen codes, for characterstobe displayed onthescreen. There should be alist of your computer's character codes in your manual On most computers you can printa character ina particular position on the 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 x3) whichis 1120. (Address 1024 is counted aszero.) 13 “On the Spectrum (Timex 2000) the information for each position on the screenis stored in several different memory locations and you cannot print characters by poking codes into the screen memory. Inside the CPU Fetcha byte from the memory Allthe computer's work is done by = sora inthe fetching bytes of instructionsanddata the sortof Paieiars from the memory, then carrying out the instructions the CPU can carry out. instructions in the CPU. There are three main areas inside the CPU: the registers where bytes of data are held while they are processed; the ALU, or arithmetic/logic unit where bytescan be added, subtractedor compared and the control unit which organizes all these activities. 5 ‘The arrangement ofthe reaistersin —_ [These pictures show the sort of instructions the 280 and 6502 chipsis different, as which the CPU can cazry out. They areall shown in the pictures below. jvery simple. Itcan fetch bytes fromthe |memory and putthem 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, suchas ; The main difference between the 280 and the 6502 chips is that the Z80 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. Asstands for“accumulator’. Fisthe “flags register’. Itholdseight IXandI¥ arecalled Ttisthe most important bits but only six of them areused. “index registers”. register inthe CPU and Each bit acts as.a signal. For They caneachhold stores byteson their wayto example, the carry flagissetto] 16bits and they are and fromthe arithmetic’ whenananswerisgreaterthan25S _used incertain logicunit. Itcanonlyhold andwillnotfitinone byteandthe _ instructions to work ‘one byte at atime sign flag shows whetheranumberis out theaddressofa positive or negative. byte inthe memory. A E 1x 8 ic y D E [SP H L PC B,C,D,E,HandLaregeneral —_$P stands for“stack PC isthe “program counter’. purpose registers where bytes _ pointer”. Itisa 16-bit Itis a 16-bitregister andit canbe storedontheirwaytoor _registerandstoresthe _ holds the address of the next fromthe memory.Eachcanhold addressofthelast itemin byte tobe fetched fromthe onlyone bytebuttheycanbe themachinestack-the memory. Thenumberinthe grouped together in pairs,e.g. placewheretheCPU —_—_programcounterincreases 14 BC,DEorHLtoholdtwobytes. —storestemporarydata. byoneeachtimean instruction is carried out. -_S Transfera Jump to registerto instruction 6 i another, adding two numbers and displaying the resulton the screen, involves overa 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 ROMor The 6502 registers bytefrom one F “Flip the bits’ thatis, make all the 1s into Os andall the \ Move all the bits one place tothe right RAM, loadsa 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 bytesinthe registers, but the ALU and control unit carry out their work automatically and you cma tell them whatto do. The main registers in the 6502 are the same as those in the 280, but some of them arecalled by different names. Ais the “accumulator” where bytes are stored on their way toand from the ALU, Itisthe same as the accumulator in the 280 and can hold only one byte. Xand ¥ are“index registers”. They are used in certain instructions to work outthe address of a byte of data. They can alsobeused as general purpose registers to hold bytes temporarily. Thisis the ninth bit of the stack pointer (register S). Pstands for “processor status register" andithas the same functionas the flags register in the Z80. It contains eight bits, sevenof which are used. Each bit is set to ]torecorda certain condition, such as whether a number is positive or negative. PCis the “program counter” andit worksinthe same way asthe PCregisterin the 280, Sisthe “stack pointer”. It stores the address of the last item onthe 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 | is wired up to thes register. This represents the page number of the address, so inthe 6802, the stack is always in page one of the memory. The numberin the stack pointer gives the position on the page. 15 16 Giving the CPU instructions Aprogram in machine code consists ofa list of instructions telling the CPU exactly what to do with bytes inthe registers, You canuse only the instructions that the CPU understands, so for computers witha 780 or Z80A microprocessor you must use instructions from the Z80 instruction set and for computers witha 6502, 6502A or 6510 microprocessor, you must use 6502 instructions. There isa list of Z80and 6502 instructions at the back of this book, Opcodes can be written as mnemonics ~ short words which represent what they do— orasthe hex equivalents of the computer's binary code for each instruction. For example, LD A onthe 280 and LDA onthe 6502 are the mnemonics for “load a byte into the accumulator”. The same opcodes in hex are 3E for the 280 and A9 for the 6502. OPERAND Most machine code instructions consist of twoparts: an “opcode” and an “operand” The opcode tells the CPU what to do andthe operand tells it where to find the datato work on, (The word operand means “object on which an operation is performed”) Each opcode is an instruction from the instruction set. These are hex codes. Mnemonicsare much easier to 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 thentranslate them to hex Here are two machine code instructions in mnemonics, one for the 280 and one forthe 6502. They both tell the computer toload the number 05 hex into the accumulator (& is the *Youcan find out about assemblers on page 40, sign to indicate hex numbers). Numbersare always written in hex in machine code.On the 6802 number is preceded by a # (hash) sign to show that it isa piece of data Asimple program Here are two programs, one for the 280 and one for the 6502, which tell the CPU to addtwo numbers. They are both written in mnemonics. Strictly speaking, a program inmnemonics 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 toload and runthe version for your computer. The Z80 and 6502 programs follow the same steps, although the actual instructionsare 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. Toadd two numbers you load the first accumulator and store the result inthe number into the accumulator. Then youadd _ memory. The mnemonic opcodes for these the second numbertothe one inthe instructions are given below. Opcodes and operands for the 280 are separated bycommas ee Z80mnemonics | Meaning | Load A witha number. A stands for “accumulator” LD A,number _|_andbDisshor for load” ADD A,number | AddtoA (the accumulator), a number. [iss Meee oases - | Loada certain address withthe contents ofA (the accumulator). UOladdress).A | Adressesare always written inbrackets. 6502 mnemonics | Meaning LDAnumber | load A witha number, A stands for “accumulator” and LD isshortfor oad" ADGisthe mnemonic for the instruction “add with carry”. Ittells the ADC number computer toadd a numbertothe accumulator and to set the carry flagin the flags register ifnecessary. You can find out more about thison page 29. StAedtdeaee Store A (ie. the contents of the accumulator) at acertainaddress. STis shor for “store” and A stands for “accumulator” i This program uses , iaxindi Lohan, three opcodes: LD A, The # sign indicates program ODA and that the operandisa LD A, &02 LD (address), A piece of data ADD A, &04 LD (&7F57),A Now you can fillinthe dataandaddresses. and 4 decimal), and storing the result in Inthese examples the programsare adding _ memory location 7F57hex @hexand 4 hex (which are the same as2 “From now on, if you have aZ80 you can skip over the 6802 programs and if your computer uses 6502 instructions, ignore the 280 programs. 18 Translating a program into hex onics into hex opcodes for loading the accumulator, and their hex cod ‘When the operand is a piece of data itis called “immediate addressing”. Whenitis the address where the data is stored itis called “absolute addressing”. The list of mnemonics and hex codes at the back of 280 adding program rent versions of the S. this book includes all the instructions covered inthis book. Ifyou want to write more advanced programs you will need to geta complete list of 280 or 6502 codesand there are some suggested books on page 40. 6502 adding program Mnemonics Hex codes Mnemonics Hex codes LD A,data 3E, data LDA data AQ data ADD A,data C6, data ADC data 69data LD (address), A 32, address STA address 8Daddress 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. Z80 adding program with data 6502 adding program with data Mnemonics Hex codes Mnemonics Hex codes LDA, &02 3E,02 LDA #802 AQ 02 ADDA, &04 6,04 ADC #&04 69 04 | LD(&7F57), A 32,577F STA &7F57 8D 577F Now you can fill in the data and addresses. Thisis quite straightforward — except for the addresses. In machine code you haveto 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 havetoreverse the two pairs of digits in an address, like this. You leave outthe & 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 hexthan For example, the highest address you can have with sixteen binary digits is 65535in decimaland FFFF in hex and the highest Decimal number that can be represented by one byte (eight binary digits) is 258 decimaland FFhex.* Mostof the opcodes in the computer's instruction set are one byte long, so in hex each opcode is two digits. Addresses, ‘The first pair of hex digits is called the high order byte and it isthe 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 ofthe memory location onthe page though, take up two bytes sothey needtwo pairs of hex digits. (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 bythe 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 ofthe way machine code listings are displayed. (Neither of these programsis complete and will not work ona computer.) Hex dump Each pair of digits is an instruction, piece of data or Cintas = etcetera be 3A3O 00 00 00 00 DB O1 CB 3A38 30 07 3E 10 DS 3Aas0 SF 21 2F 39 11 saa Co 03 C5 0c 27 3Aas0 se 28 28 CD CS 3 sase 3A D3 01 4 OD 3A6O FE 00 FA 88 3A FS CD 3AGB 08 FE 44 CA 06 3B FL Assembly language listing { Address Hexcodes Mnemonics 0340 az 00” — Lox “#800 ‘This is called ahexdump. The first four digits in each line are an address and the rest of the pairs of digits are the hex codes for instructions, data and addresses. The first code in each lines stored in the address at the beginning of the line. The restof 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 O342 BD AE 05 LDA LOSAE,x line is stored in the computer's memory. ose we The next column contains the hex codes 0349 £0.0B CPx HOB for the program, followed by the 03548 DOFS BNE EFS axes Bae ranemonics. *Youcan find out how to convert binary numbers to decimal on page 28. Finding freeRAM 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 storethe program. When youtype 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 whereto store the program. Youneed to choose an area in the RAM where your machine code will not interfere with any other information stored in the memory. For instance, yournust notstore machine code in the areas reserved for use by the operating system, such as the systems variables or the stacks. Ifyoudo the system will probably crashas. your machine code will have replaced vital information which the computer needs toorganize all its work. You also have to be careful to keep your machine code separate from any BASIC program you may give the computer at the same time. If the computer crashes the only way to restore it is to switch itoffand onagainand you will lose your program. How much memory will you need? Seven y bytes. Onebyte eS Each memory location holds one byte. Itis quite easy to work out the length ofa Most machine code programs are quite machine code program ~ you just count up short and to start with a hundred bytesof thenumber of pairs of hex digits(each pair memory space will probably be plenty for takes up one byte), Forexample,the adding your machine code programs. program has seven bytes. Finding freeRAM The normal place to store machine code programsis 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. Toavoid this you can lower the top of the user RAMarea. This makes a “no-man’sland” above user RAM which the computer will notuse until youtell ittowhenyou load your machine code program. The top of user RAMiscalled 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 keepsa 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 principlesgiven below. Youshould 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. Position 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 on the page. Look up the addresses of these systems variables locations in your manual (they may be listed as RAMTOP, HIMEM, or 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 inthe systems variables holds the position number and the second, the page. Youcanuse PRINT PEEK (or your computer's command) like this to peekinto the systems variables and print outthe address of RAMTOP. Fill inthe 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 Oric it is HIMEM. These commands are followed by the address of the top of user RAM minus the number of bytes of memory you wish to reserve 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 position on the page. NEW ]]|_RAMTOP) machine code as shown above left. Check your computer's command in your manual. These commands lower the top of user RAMDby 100 locations and so reserve an area of 99 bytes for machine code starting at the address after RAMTOP. Youcan change the figure 100 toreserve more space. al "See over the page for how to lower the top of RAM onthe VIC 20, and where tostore machinecode onthe ZX81 (Timex 1000). 22 VIC 20 tip The VIC 20has no special command for changing the address stored inthe systems variables. Here are the instructions for lowering the address of the top ofuser RAM onthe VIC. ‘The address is held in systems variables 85 and 56. Remember, the second location holds the page number. ‘To lower the top ofuser 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 | fromthe value held thereand then pokes the new value back into location 56. 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 cornmand: PRINT PEEK(55) + PEEK(56)*256. 2X81 tip On the ZX81 the best place tostore machine code programs.is at the beginning of user RAM. Todo this you type a REM statementas the first line of the hex loader program given on page 24 and fill it with as many digits as there are bytes in your machine code program. Each of the digits inthe REMstatement takes up one location inthe memory. Now youcanpoke your bytes of machine code into the locations reserved by the digits in the REM The first byte of machine code will be storedin location 16514, lM aa La User RAM starts at location 16509, Todo this you need to know the address where the first digitis stored. User RAM starts at location 16509 and the computer needs two bytes to hold the REMline number, one for REM, one for NEWLINE and one torecord the length of the line, so the first digitis in location 16514. Other places to store machine code ~ of There are afew other placesinthe memory where store machine code, aegate potting wet Poo. instance, if you are not planning on. saving your program, you can store tin the creating any user-defined graphics, io ae could store it in the area set aside for this. buffer, orifyouarenct = User defined Cassette graphics area. 5 Loading and running a program The next fe To give the computer a mat area of memory that you ha RAMTOP). On most computers you short BASIC program called a “he: converts each byte of machine code t memory. There isa hex loader F change the address for the answer to the adding program for your computer. There isalso one more instru n (see be the program on page 18. pyte into the 12 Choosing an address for the answer Data produced bya machine code they will not get mixed up with the program program, suchasthe answer tothe sumin _ itself. The best place is right atthe the adding program, iscalled“databytes”. beginning of the area you have reserved for Itis important to store data bytes where machine code, in front of the program. : 5 For example, ifyouhaveloweredthetopof store the data byte and the program would user RAMto, say, location 16000, the first Start in location 16002. You will needto address of the area for machine codewill _ convert the address for the data byte to hex be location 16001. Thisis where youwould so youcaninsertitinthe program. Address 16001 is 3E81 inhex. To convert the addresstohex youdivideby To convert these to hex you divide by 16 286. The answer isthe decimal page and then convert the answers and numberand the remainder isthe position _remaindersto hex digits as shownabove. onthe page (see page 11). The returninstruction 280 mnemonics Hex codes LD A, &02 3,02 ADD A,&04 S 6,04 32,577F Atthe endofevery machine codeprogram _itleft off, Without this command, the you must always have the instruction RET computer would carry on attempting to (forthe 280) or RTS (for the 6502). This follow an instruction for every byte it found makes the computer stop running the inthe memory and the system would soon machine code program and return towhere crash.” 23 *There is more about the return instruction on page 35. 24 Hex loader program Here is the program for loading machine code into the computer's memory. To use this loader youput the hex codes of your machine code program in line 160, followed by the word END, as a signal to tell the computer there isno more data. Atline 40, the computer reads pair of hex digits, converts them to adecimal numberin lines 70to 110 andthen pokes that number into the memory in line 130." 10 PRINT “ADDRESS WHERE MACHINE CODE 15 10 BE STORED?» 20 INFUT A 30 LET cao 40 READ HE 50 IF HS="END" THEN GoTo 180 60. IF LEN(HS)<52 THEN GOTO 17¢ 70 LET x=(Astcie)—aar x16 BO IF ASC (HS) 957 THEN LET x= XASC (HS) 55) #16 90 LET V=ASC (RIGHTS (8.19) 100 IF Y255 THEN GOTO £7: POKE arc. x Let cac+1 REM SAMPLE DATA ONLY DATA EF.F&,E2,A9,END PRINT “BAD DATA" Atline 70, the computer converts the first digit in HS to its ASCII code using the BASIC word ASC. Itthen converts the ASCII code toa decimal value by subtracting 48, or for codes over 57, by subtracting 55, asshown inthe chart above. Thenit multiples by 16 because the first hex digit represents the number of 16s and puts the answerinX. Aisthe address of the first location where ‘youwishtostore your program. Cisacounter. ‘Puts first pair of hex digits inline 160 into HS. ‘Tests HS for word END, the signalto indicate end of data. PALS Chocks imate iis Hi cains wo il and ifnot, goes toline 170. ‘Converts first hex digit toa decimal number and stores in X. Converts second hex digit to adecimal number, ¥, andadds to X. Checks for bad databy making sure decimal number in Xis between and 258, First time, C=0, so pokes Xintomemory location A. ‘Adds one to C, so pokes decimal value of sor) 49 ————_exthexcode into memory location A+1 Back to read next hex code. Put your hex codes here, followed by signal word END. Prints this if it finds bad data in lines 60 or 120, then stops. At line 90it uses the same methodto convert the right-hand digit toan ASCII code and storesit in Y. Inlines 100 and 110it changes ¥ toa decimal number by subtracting 48 or 55 as before, andaddsitto X. (This time it does not multiply by 16 asitis the digit which represents Is inthe hex number.) The value stored inXis the decimal equivalent of the pair of hexdigits. *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 ZX81 (Timex 1000) and Ataricomputers. Using the loader Now you canuse the hex loader to try out the machine code adding program. This is nota very exciting program, butit is simple and it shows you how machine code works. Typethe hexloader into your computer. Atline 160, replace the sample data with the hex codes for the adding program, as shown below. Data for the hex loader Smee ENDsignal tocomputer. Replace Ib and hb with the two bytes of the address forthe answer. 280 ] 160 2.1b, hb, C9, END 6502 | 160 DATA A9.02, 69,04,8D,1b,hb.40, END. These are the hex codes for the adding answer will be stored in your computer. program. Youneed to replace the letterslb | Remember to put the bytes in reverse (low order byte) and hb (high order byte), order, i.e. low order byte (position on page) withthe two bytes ofthe address wherethe _ followed by highorder byte (page number). Running the hex loader ets ADORESS WHERE MAINE cape is 10 Ge STORED? 21600 Now type RUNto run the hex loader you are storing the answer. Type this program. Whenit asks youfortheaddress, address as a decimal number asit will be type in the firstlocation after theonewhere used with the POKE command. Running the machine code program Desi s5s ee ay PRINT USE CLeu02> SYSCIE002) These are some of the commands used on _cifferentcomputers. The command to tell the computer tostart first byte of the programis stored. Check runninga machine code programvarieson _ this command in your manual. Whenthe 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 outthe decimal address of the location where the machine code instructions. 25 Seeing the result ‘The computer carries outthe machine code _ have to use PRINT PEEK with the address of instructions and stores the answer inthe the answer. The result will be the answerin location youtold itto. To see the result you decimal. Programs to write Younow 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 writinga programto add 25 and 73 (decimal) and store the result inthe The adding programwill only add ROSEEY numbers which total less than 255. 2. See if you can write a programtoadd On page 28 you can find out how to. 64and 12and 14 (decimal) and store the add larger numbers. resultin the memory. Machine code checklist 1. Write your program inassembly language and convert any datatohex. 2, Look up the hex code for each of the mnemonics (there isa list of the mnemonics and hex codes atthe back of 6. Fillinthe addresses in the program— remember to put the two bytes inreverse order. (See pages 18-19.) ‘ 2. Type inthe hex loader (youcould save ae 2 this program ontape) and fillinthe hex DD codesiintine 160 fotlowed by the END sigmal. (See page 24.) 3. Add the return instruction tothe end of the program. (See page 23.) 4, Count up the number of bytesand reserve your free RAMarea. (See pages 20-22.) Make a note of the addresses of 8. Run the hex loader and input the data bytes andof the address decimal address of the first location where you have stored the where you wish to store the machine pee code. (See page 25.) 9. Run the machine code programusing your computer's command with the address (in decimal) of the first location where the machine code isstored, (See page 25.) Ifyou change the datain the hex loader youhave to run the program again to poke the new bytes into the memory. 5. Work out what memory locations you need for data bytes and convert the 26 addresses to hex. (See page 23.) Adding bytes from memory In the previous program the data was included in the program itself. This iscalled immediate addressing. Sometimes, though, youmay want to tell the computer to do something with data stored in 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, ‘These are justtwo ofthe severaldifferent. modes". There is adifferent hex code for waysin which you cantell 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. ‘280 program Mnemonics | Hex codes Meaning LD A,(address1) | 3A,address1 Putthe number in address | intothe accumulator. | [OBA —*| a7 Putthe number in the accumulator into register B. [LD Ajladdress2) | 3A, address 2 | Putthe number inaddress 2intothe accumulator. | ADD AB 80 Add the number in register Bto [LD (address3),A__| 32,address3 | Store the contents of the accum RET [cs | Return = Toadd two numbers frommemory you straight from the memory, though, so you have toload them intothe registersfirst.For _have to put the first number into A and then this you canusetheaccumulator(A)and _transferittoB. register B. You cannotload 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). 27

You might also like