Machine Code For Beginners
Machine Code For Beginners
Machine Code For Beginners
Usbome CompulerBooks
USBORNE INTRODUCTION TO
~@~{}oTI~~ ~@@~
v©lli 10~@TIliJliJ~lli£)
Usa Watts and Mike Wharton
1D A is the mnemonic
instruction. for an instruction.
LO 4, 02-~------'
instruction.
1.
The computer's memory Memory addresses
The easiest way to think of the computer's memory is as lots of little boxes, each of Inside the computer, memory addresses are
which can hold one byte, i. e. one instruction or piece of information in machine represented by two bytes of computer code, i.e. 16
pulse or no-pulse signals or "bits". The largest
code. Each box in the memory is called a "location", and each location hasa
possible memory you can have on a
number, called its "address", so the computer can find any box in the memory. microcomputer which uses a Z80 or 6502
Different areas of the memory are used for storing information for different tasks microprocessor is 64K (ROM and RAM combined).
and a chart giving the address w here each area starts is called a "memor y map". - This is because the biggest number you can make
When you are programming in machine code you have to tell the computer with 16 binary digits is 65535, so this is tb2 highest
where to find or store each instruction or piece of information. You do this by giving possible address. This gives 65536 locations,
it the addr ess of a memory location. You even have to tell it w here to store the numbered from 0 to 65535. Each location holds one
machine code program itself, so you need to get to know the memory map ofyour byte, 1024 bytes make a kilobyte (K) and 65536
bytes equal 64K (65536 + 1024 = 64).
computer.
Buffers
1 2 2 6
In the decimal system the first digit on the
~ 4 C A
In a hex number the first digit on the right
These are temporary stores to hold data coming in from
the keyboard, or being sent to a printer or cassette. right of a number shows how many Is there also shows the number of Is but the next
are, the second shows the number of lOs, . digit shows the number of 16s, and the third
the third, the number of lOOs (10 2 ), etc. digit shows the number of 256s (16 2 ).
Machine stack
Also called the processor stack, the CPU usesthese
locations to store addresses while it is working ona
machine code program.
Converting hex to decimal
To convert a hex number e .g. 4CA, to
decimal, look up the decimal for each of 4
I ~5~6S~1~~
~
12
6s.\--1~~sI
10 Decimal value l~
l1iP
x 256 x 16 ~ ,...~_
the digits in the number. Then multiply
BASIC stack
each digit by the value of its position in the 1024 + 192 + 10 = 1226 Can you convert
Also called the GOSUB stack, this is for storing the line MCA is 1226 m decimal. &A7 to decimal and
numbers used in BASIC GOSUB and GOTO commands. number and add up the answers. decimal 513to hex?
(Answers pa ge44')J
Calculator stack Decimal to hex
This is the CPlTs temporary store for numbers used in To convert a decimal number e.g. 1226, to 1226 + 256 = 4 .............. .... 4is4 inhex
calculations. hex, first you divide by 256 to find how many remainder 202
256s there are in the number. Then you
divide the remainder by 16 to find the 202~ 16= 12 ...... .. ........ .. 12isCinhex
Systems variables
These are a series of memory locations where the CPU number of 16s and the remainder from this remainder 10 ... ...... .... ....... 10 is A in hex
stores information about what is happening inside the sum gives the number of Is. Finally, convert
the answer to each sum to a hex digit. * 1226is4CAinhex
computer. For instance, there are separate locations for
recording the current position ofthe cursor on the
screen, which key is being pressed and the address of Converting hex addresses
the area where variables are stored. In a hex address, e.g. 5C64, the two left-hand digits show which page (see opposite) the
...
176 decimal equivalents
..... ... .... of bytes of
computer code. Most computers use the ASCII code
To tell the computer to look in a memory Now find the screen memory for your (pronounced "askey"), to decide which
location you use PEEK (or your computer's Try writing a short program using a FORI computer, then try poking numbers into numbers represent which characters, but
command) with the address of that location. NEXT loop, like the one in the centre above, screen memory locations. You do not need some, such as the ZX81 (Timex 1000) use
To see the result on the screen, use PRINT to print out the bytes from a series of to use PRINT PEEK because bytes stored in different numbers. The VIC 20 has a special
PEEK, or store the result in a variable using locations. Look at your computer's memory the screen memory are automatically set of numbers, called screen codes, for
LET and then print out the variable, as map and experiment with addresses in displayed on the screen. This time the characters to be displayed on the screen.
shown above left. different parts of the memory. computer interprets the number as the There should be a list of your computer's
code for a character.' character codes in your manual.
Poking
10 L E T J=screen
Put an address in xxxxxxxxxx xxxxxx xxxxxxxxxxxxxxxx
~
addres s your computer's x x x xx x x xxx x xx x x xx x xx ~;}; x ~:;< x >:x xx xx
This tells the screen memory xxxxxxxxxxxxxxxxxxxxx x xxxxxxxxxx
computer to put60 20 L ET C=3 3
30 POKE J ,e here. xxxxxxxxxxxxxxxx x xxxxxxxxxxxxxxx
PQl(E 167 6 3 . 60
PRINT PE EV( 1676 3)
in location 16763.
40
50
L ET J = J +1
LET C=C+l
'-,/'-.-......._/'-..:~'~t~.."'ll "Location 1120.
60
60 IF C< = 125 T HEN GDTO 30 First location in screen memory.
70 STOP
Use PRINT PEEK
to seethe result. On most computers you can print a
Try a short program like the one above to
print your computer's character set. The character in a particular position on the
The picture above shows you how to use short program like the one above to poke program uses ASCII codes, starting with 33, screen by working out the address of the
POKE. You can poke anywhere in RAM, but several numbers into a series of locations in the code for!, and ending with code 90. location for that position. For example, if the
if you poke new values into the area user RAM. Other numbers in the range 0-255 are for screen memory starts at location 1024 and
reserved for use by the operating system The numbers you poke must be between special keys such as SPACE and DELETE, the computer can print 32 characters on a
you may disrupt the workings ofthe oand 255, the highest number than can be for printing the alphabet in inverse or line, the address for the first position on the
computer. You can restore it to normal by represented with eight binary digits (one flashing characters, and for graphics fourth line will be 1024+(32 x 3) which is
12 switching off and on agaln. Try writing a byte of computer code). characters. 1120. (Address 1024 is counted as zero.) 13
*On the Spectrum (Tirnex 2000) the information for each position on the screen is stored in several
"Some computers use different commands, e.g. the BBC uses a? mark. Check your manual. different memory locations and you cannot print characters by poking codes into the screen memory.
Inside the CPU Add two
bytes. Transfer a
byte from one "Flip the
All the computer's work is done by Jump to register to that is, make
instruction 6. another. all the 1sinto
fe tching bytes of instructions and data
Osandallthe
from the memory, then carrying out the Os in to 1s.
instructions in the CPU
There are three main areas inside the
CPU the registers where bytes of data
are held w hile they are processed; the
ALU, or arithmetic/logic unit where
bytes can be added, sub tracted or
compared, and the control unit which
organizes all these activities.
The arrangement of the registers in pictures show the sort of instructions adding two numbers and displaying the RAM,loads a data byte into the registers
the Z80 and 6502 chips is different, as CPU can carry out. They are all
IWJllC.n {[le result on the screen, involves over a and then performs the operation specified
shown in the pictures below. simple. It can fetch bytes from the hundre d simple steps like these and the by the instruction. In machine code, you
Imemol1' arId put them in the registers, move CPU can carry out over half a million eachtell the CPU what to do with the bytes in the
one registerto another, process second. registers, but the ALU and control unit carry
ITn,>mm the ALU and store the results in the For each operation the control unit out their work automatically and you cannot
TheZ80registers ~~~~E~ve~n~t~h~e~~~~~,~su~c~h~as ~________ J-____ ~f~et~c~h~e~san~~~~~~~~~~~~o~r~~t~e~ll~th~e~m~w~h~at~t~o~d~o~.____~__~____~
The main difference between the Z80 and the 6502 chips is that the ZeO has more registers. The 6502 registers
This means that bytes can be stored temporarily in the CPU, whereas in the 6502 they have to The main registers in the 6502 are the same as those in the Z80, but some of them are called
be sent back to the memory. by different names.
A stands for "accumulator". F is the "flags register". It holds eight IX and IY are called A is the "accumulator" P stands for "processor
It is the most important bits but only six of them are used. "index registers". where bytes are stored on status register" and it has
register in the CPU and Each bit acts as a signal. For They can each hold their way to and from the the same function as the
stores bytes on their way to example, the carry flag is set to 1 16 bits and they are ALU. It is the same as the flags register in the Z80. It
and from the arithmetic! when an answer is greater than 255 used in certain accumulator in the Z80 and contains eight bits, seven of
logic unit. It can only hold and will not fit in one byte and the instructions to work can hold only one byte. which are used. Each bit is
one byte at a time. sign flag shows whether a number is out the address of a sella 1 to record a certain
positive or negative. byte in the memory. X and Y are "index condition, such as whether a
registers". They are used in number is positive or
/
I
A
1/ hil I
IX
I"'" certain instructions to work
out the address of a byte of
data. They can also be used
V ' 11
IY
"'- as general purpose
B ~ registers to hold bytes
l 11 I temporarily. PC is the
"program
V V
E SP "'- counter" and it
D This is the
t I 11 I ninth bit of
the stack
works in the
same way as the
"'-
~I
V pointer
1-1 L PC PC register in
(register SI.
I I I theZ80.
IL: V
B, C, D, E, H and L are general
purpose registers where bytes
SP stands for "stack
pointer". It is a 16-bit
"
PC IS the "program counter".
It is a 16-bit register and it
S is the "stack pointer". It stores the address of the last item on the
stack - the special area in the RAM where the CPU stores data. In the
can be stored on their way to or register and stores the holds the address of the next 6502 the stack pointer is an eight-bit register. In order to store
from the memory. Each can hold address of the last item in byte to be fetched from the addresses a ninth bit kept permanently at 1 is wired up to the S
only one byte but they canbe the machine stack - the memory. The number in the register. This represents the page number of the address, so in the
grouped together in pairs, e.g. place where the CPU program counter increases 6502, the stack is always in page one of the memory. The number in
14 BC, DE or HL to hold two bytes. stores temporary data. by one each time an the stack pointer gives the position on the page. 15
instruction is' carried out.
Giving the CPU instructions A simple program
A program m machine code consIsts 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
of a list of instructions telling the CPU is called an assembly language program and one which uses hex codes is called machine
exactly what to do wIth bytes in the code. Over the page you can find out how to translate the programs to machine code, and
registers. You can use only the on the next few pages, how to load and run the version for your computer.
instructions that the CPU
The Z80 and 6502 programs follow the same steps, although the actual instructions are
understands, so for computers with a different. * In the 6502, data on which calculations are to be carried out must always be
Z80 or Z80A microprocessor you placed in the accumulator. In the Z80 it is placed in the accumulator, or for big numbers, in
must use instructions from the Z80 register pair HL.
instruction set and for computers
with a 6502, 6502A or 6510 Most machine code instructions consist of
microprocessor, you must use 6502 two parts: an "opcode" and an "operand".
instructions. There is a list of Z80 and The opcode tells the CPU what to do and the
6502 instructions at the back of this operand tells it where to find the data to
work on. (The word operand means "object
book. on which an operation is performed".) Each
opcode is an instruction from the instruction
set.
To add two numbers you load the first accumulator and store the result in the
These are mnemonics. These are hex codes. number into the accumulator. Then you add memory. The mnemonic opcodes for these
the second number to the one in the instructions are given below.
es and
ZBO mnemonics operandsforthe
zaD are sepal·at"d~lf.
LD A, number Load A with a number. A stands for "accumulator" bycom
and LD is short for "load".
! ADC is the mnemonic for the instruction "add with carry". It tells the .
ZBO ADCnumber computer to add a number to the accumulator and to set the carry flag m
the flags register if necessary. You can find out more about thlS on page 29.
Here are two machine code instructions in sign to indicate hex numbers). Numbers are
mnemonics, one for the Z80 and one for the always written in hex in machine code. On and 4 decimal), and storing the result in
Now you can fill in the data and addresses.
6502. They both tell the computer to load the the 6502 a number is preceded by a # In these examples the programs are adding memory location 7F57 hex.
number 05 hex into the accumulator (& is the (hash) sign to show that it is a piece of data. 2 hex and 4 hex (which are the same as 2
16 17
*From now on, if you have a 280 you can skip over the 6502 programs and if your computer uses 6502
"You can find out about assemblers on page 40. instructions, ignore the 280 programs.
Translating a program into hex More about hex codes
The only way to translate the mnemonics into hex codes is to look upeach Machine code programs are written in hex rather than decimal numbers because the
mnemonic in a chart, There is a chart of mnemonics and hex codes at the back ofthis binary numbers used in the computer's own code translate more neatly to hex than
Cimal
~
book. You have to be careful, though, as there are several different hex codes for
.~ Deci~
each instruction depending on whether the operand is a piece of data, an address or d i,f f
the name of a register, For example, here are some different versions ofthe _ F\
opcodes for loading the accumulator, and their hex codes, ~I . Hex
Z80 6502 For example, the highest address you can number that can be represented by one
have with sixteen binary digits is 65535 in byte (eight binary digits) is 255 decimal and
Mnemonics Hex codes I Mnemonics Hex codes decimal and FFFF in hex and the highest FFhex,'
i
LD A.data 3E.data
-- -
LD A. (address)
-
Here are the hex codes for the Z80 and 6502 code and those in hex are called object Looking at machine code programs
adding programs, Instructions in code, Machine code programs in magazines look very confusing until you work out how they are
mnemonics are sometimes called source presented. Below there are two examples of the way machine code listings are displayed.
(Nei!herofth_programs is complete and will not work on acomputer.)
&mpm~~.u
8502 adding program with date Hex d ump _ - . . . .~..... This is caDeda hexdump. The first foor
(.,-- "port~ulddn."'''''' dlgitII in each line are an address andthe
Mnemonics Hex codes :sA3O 00 00 00 00 D8 01 CB IF IeIII of the pairs of digits are the hex codes
3A38 CB IF 30 07 :lE 10 D3 00 forinslructiolla,dataandaddresses The
3A4O
:5A48
CF
DO
37 :sF 21 2F
01 co 03 cs
3'P 11 00
OE Z7 71
first code in -
---'"line
.,
' ored'In the'
IS 81
LOA #&02 A902
3ASO lA FE se 28 28 CD cs :sA addrea at the beginning ofthe line. The
ADC #&04 6904 :: ~ : ~ : ~ ~ ~ ~ IeIIIofthecodes are stored in the locations
3A68 os FE ' " CA "" 38 FI 71 following that address.
STA &7F57 80 577F Assembly languagelllltlng This listingincludes hex codes and
(Address Hexcodes;, Mnemcmics mnemonics, The first number in eachline
Now you can fill in the data and addresses, 0340 A2 00 ~ LD. _ is the address where the first byte in each
This is quite straightforward - except for have to reve rse 0342 BD 4E 03 LOA 11034£, X line is stored in the computer's memory.
the two pairs of d igits 034:5 9D co B3 STA IrB3CO, X
the addresses, In machine code you have to 0348 Ea INX
The next co1umn contains the hex codes
reverse the order of the two pairs of digits in an address, like this. 0349 EO 08 CPX 4Ma08 for the program. followed by the
which make up an address, You can find out 0348 DO F:; BNE ~ mnemonics.
034D 00 BRk
18 more about this on the opposite page, You leave outthe & 19
and # signs in the hex
code version. *You can find out how to convert binary numbers to decimal on page 28.
Finding free RAM Lowering the top of user RAM
There are several things to do before you can load and run the addmg program on 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
page 18. First you need to choose an area in the memory in which to store the . instructions for doing this vary on different computers, but most follow the principles given
program. When you type in a BASIC program, the BASIC interpreter automatlcally below. You should check how to change the top of RAM in your manual though, as your
stores your program in user RAM. When you give the computer a machine code computer may use different instructions, or may even have an easier way to make space
program, you bypass the mterpreter so you have to tell the computer where to for machine code. .
store the program.
You need to choose an area in the RAM where your machine code will not Page
interfere with any other information stored in the memory. For instance, you must number . .
not 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 crash as
your machine code will have replaced vltal informatlon whlch the computer needs
to organize all its work. You also have to be careful to keep your machmecode
separate from any BASIC program you may give the computer at the same time. If
the computer crashes the only way to restore itis to switch it off and on again and
you will lose your program. The address of RAMTOP takes up two just top of user RAM). The computer stores
consecutive locations in the systems the two bytes of the address in reverse
variables, one for the page number of the order - first the position on the page, then
How much memory will you need? location and one for the position on the the page number, so the first location in the
page. Look up the addresses of these systems variables holds the position
systems variables locations in your manual number and the second, the page.
(they may be listed as RAMTOP, HIMEM, or
Each memory
PR INT PEEK<address l)+PEEK
location holds
(add r e ss 2)*256
one byte.
" ~'2-S\'2-
It is quite easy to work out the length of a Most machine code programs are quite ~'2-S\'2- ...."" '2>~'2-S~~
machine code program - you just count up short and to start with a hundred bytes of
the number of pairs of hex digits (each pair memory space will probably be plenty for You can use PRINT PEEK (or your This command automatically converts the
takes up one byte). For example, the adding your machine code programs. computer's command) like this to peek into two bytes ofthe RAMTOP address into a
program has seven bytes. the systems variables and print out the decimal address by multiplying the page
address ofRAMTOP. Fill in the addresses number by 256, then adding the position on
of your systems variables. the page.
Fi nding free RAM
The normal place to store machine code
programs is at the top of user RAM, the CLEAR ramtop address - 100
place where BASIC programs are
stored. You have to make sure, though,
\ Spectrum
that the machine code will not get mixed
HIMEM ramtop address - 100
up with any BASIC programs. To avoid
this you can lower the top of the user
RAM area. This makes a "no-man's land"
above user RAM which the computer
...
Most computers have their own special
' - Oric
~
will not use until you tell it to when you command for changing the address of the your computer's command in your manual.
load your machine code program. top of user RAM. For instance, forthe These commands lower the top of user
The top of user RAM is called Spectrum (Timex 2000) the command is RAM by 100 locations and so reserve an
RAMTOP, or H1MEM, or just top of CLEAR and for the Oric it is HIMEM. These area of 99 bytes for machine code starting at
memory. You can find out how to lower commands are followed by the address of the address after RAMTOP. You can
RAMTOP on the opposite page. the top of user RAM minus the number of change the figure 100 to reserve more space.
20 bytes of memory you wish to reserve for ,21
""See over the page for how to lower the top of RAM on the VIe 20, and where to store machine code
on the ZXSI (Tirnex 1000).
VIC20tip zxa1 tip
Loading and running a program
The VIC 20 has no special command for On the ZX81 the best place to store The next few pages show you how to load and run the adding program on page 18.
changing the address stored in the machine code programs is at the To give the computer a machine code program you have to poke each byte into the
systems variables. Here are the beginning of user RAM. To do this you area of memory that you have chosen for storing machme code (e.g. above
instructions for lowering the address of type a REM statement as the first line of RAMTOP). On most computers you can only poke decunal numbers so you use a
the top of user RAM on the VIC. the hex loader program given on page short BASIC program called a "hex loader" to do this for you. The hex loader
24 and fill it with as many digits as there converts each byte of ma'c hine code to a decImal number, the n pokes it into the
are bytes in your machine code memory. There is a hex loader program over the page. First, though, you need to
program.
change the add ress for the answer to the adding program, to an address suitable
fo r your computer. There is also one more instruction (see below) you must add to
5 REM 1234 5 6 7 the program.
- - Seven bytes
Ch oosing an address for the answer
Each of the digits in the REM statement Data produced by a machine code they will not get mixed up with the program
takes up one location in the memory. program, such as the answer to the sum in itself. The best place is right althe
The address is held in systems variables Now you can poke your bytes of the adding program, is called "data bytes". beginning of the area you have reserved for
55 and 56. Remember, the second machine code into the locations It is important to store data bytes where machine code, in front of the program.
location holds the page number. reserved by the digits in the REM.:-..._--..;- ,
statement.
( POK E 56 , PEEK (56} - 1
] Th e first byte
of machine
code will be
sto red in
location 16514.
To lower the top of user RAM by 256
locations, i.e. one page, use the direct User RAM
command shown above. This makes the starts at
For example, if you have lowered the top of store the data byte and the program would
computer peek into location 56 (the one location user RAM to, say, location 16000, the first start in location 16002. You will need to
which holds the page number). It 16509. address of the area for machine code will convert the address for the data byte to hex
subtracts I from the value held there and be location 16001. This is where you would so you can insert it in the program.
To do this you need to know the address
then pokes the new value back into where the first digit is stored. User RAM
location 56. In other words, it reduces the 16001 266 62ntmainderl29 62 T 16-
starts at location 16509 and the computer 3183_ 1418Emhex. Address
page number part ofthe address by I. To 16001 is
needs two bytes to hold the REM line 3E81 in hex.
see the new address of the top of user 'number, one for REM, one for NEWLINE 129 16 - 8 remainder
RAM type this command: 8188_ 1181 m hex.
and one to record the length of the line,
PRINT PEEK(55)+ PEEK(56)'256. so the first digit is in location 16514. To convert the address to hex you divide by To convert these to hex you divide by 16
256. The answer is the decimal page and then convert the answers and
number and the remainder is the position remainders to hex digits as shown above.
Other places to store on the page (see page 11).
Cassette
machine code Userdefined
graphics area. buffer
There are a few other places in the The return instruction
memory where you can store machine
code, if you are not using them. For Z80 mnemonics Hexcodes 6502 Mnemonics Hex codes
instance, if you are not planning on LD A,&02 3E,02 LDA # &02 A902
saving your program, you can store it in ADD A,&04 C6,04 ADC # &04 6904
the cassette buffer, or if you are not LO (&7F57), 32,577F STA&7F57 ...:_,80 577F
creating any user-defined graphics, you
could store it in the area set aside for this.
Look in your manual to find the
addresses of these areas in the RAM. At the end of every machine code program it left off. Without this command, the
Your manual may also suggest suitable you must always have the instruction RET computer would carry on attempting to
places in your computer's memory for (for the Z80) or RTS (for the 6502). This follow an instruction fo r every byte it found
storing machine code. You should look makes the computer stop running the in the memqry and the system would soon
out, too, for tips in magazines and books. machine code program and return to where crash. * 23
,2
' There is more about the return instruction on page 35.
Hex loader program Using the loader
Here is the program for loading machine code into the computer', memory. To use this Now you can use the hex loader to try out the machine code adding program. This is not a
!older you put the hex codes of your machine code program in line 160, followed by the very exciting program, but it is simple and it shows you how machine code works. Type the
word END, 88 a sitJnal to tell the computer there is no more data. At line 40, the computer hex loader into your computer. At line 160, replace the sample data with the hex codes for
I8IIds a pair of hex digits, converts them to a decimal number in linea 70 to 110 and then the adding program, as shown below.
poba that number into the memory in line 130.·
Data for the hex loader
10 PRINT "ADDRESS _ RE I1ACHlNE
Replace Ib and hb with the two END signal
CODE IS TO BE STORED"" A l8 tbaaddrel8ofthellratlocationwhere bytes of the address forthe to computer.
20 I NPUT A _ _ _ _ _ _ _ _ _ _ _ _ _ you wiahIOlllOreyourpragram.
answer.
30 LET Cooo _ _ _ _ _ _ _ _ _ _ _ _ _ CisaCOll11ler.
l-=
:50 I F _ " END " THEN GOTO 180 T8118HSforWOldEND, theaigJ1al IO
indIca18 eftdof data.
60 IF LEN CH.>02 THEN BOTO 170 ~ 6502 160 DATA A9. 02 .69, 0 4.8D.l b ,hb. 60 ,ENO
10 LET x- CASe CHS >- 4e >*16 CbeclalIo make II\re HSoomaills twoc:llgila,
IJId If IlOl, goes 10 line 170.
These are the hex codes for the adding answer will be stored in your computer.
eo IF ASCCH. > :S7 THEN LET x- c:oa-t. llrat hexdigilloadec:imalnumber program. You need to replace the letters lb Remember to put the bytes in reverse
CASCCH.>-:S:S).1 6 lJIdatoreamll (low order byte) and hb (high order byte), order, i.e. low order byte (position on page)
90 LET V-ABC(R IBHT. CHS. ll) }-ecmvertaaeccmdhexdlgilloadec:imal with the two bytes of the address where the followed by high order byte (page number).
lOO IF V :se THEN LET X-X+V-4B number, Y, IJId edda loll
1 10 IF V :S1 THEN LET X-X+V-!i5 Cbeclalforbad~bymaki11g11\re Running the hex loader
120 I F X 0 OR X 2:s:s THEN GOTO 170 dec:imalnumberinXill belw_,OIJld2SS.
130 A+C. X _ _ _ _ _ _ _ _ _ _ _ _ Flnttlme,C- O,..,pobsXinIomemory
POl(£
ka1ioIIA.
140 LET C-C+ I - - - - - - -- ----AddaOMIoC,..,pobsdec:imalvaIueof
1:50 GOTO 40 _ _ _ _ _ _ _ _ _ _- , I1U1hexoodeinlomemoryIocationA+ l .
'--lIackloreadnuthexoode.
llilS RE" S AHPLE DATA ONL V _
_ _ _ _ _ _ Plllyourhexoodeehere,foIlowedbyaigJ1al
160 DATA EF . F. , E2 . A9 . END WOIdEND.
110 PRI NT "BAD DATA" - - - - - - - - - Prinlatilislfllflndabad~inliDes60or
lao,lhenllOp"
l eo STOP
Now type RUN to run the hex loader you are storing the answer. Type this
How the loader works program. When it asks you for the address, address as a decimal number as it will be
type in the first location after the one where used with the POKE command.
Hex o 2 3 4 5 6 7 8 9 A B c D E F
Running the machine code program
r---~~rnroummn~~
ASC If Decimal
:5: SI -49 = .3 x 16=48
E = 69 - 55 - /4
[ PRINT PEEK<1 6001l ] [ :RINT P EEK (16001l J In the previous program the data was included in the program itself. This is called
immediate addressing. Sometimes, though, you may want to tell the computer to
do something with data stored in its memory. In this case, the operand part of an
instruction will be an address telling the computer where to find the data. This is
The computer carries out the machine code have to use PRINT PEEK with the address of called absolute (or direct, or extended) addressing.
instructions and stores the answer in the the answer. The result will be the answe r in
location you told illo. To see the result you decimal. Immediate Absolute
addressing add ressing
Programs to w rite
You now know enough machine code to write some simple programs. There is a
checklist at the bottom ofthe 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 ~ ;...-::..:.::..;/"-----.---~-------~ These are just two of the several different modes". There is a different hex code for
(decimal) and store the result in the ~
ways in which you can tell the computer each instruction depending on the
, The adding program wi ll only add ( where to find the data to work on. The addressing mode you are using.
memory. ~~~ numberswhi chtotallessthan255. different ways are called "addressing
2. See if you can write a program to add 'T On page 28 yo u can find out howto
64 and 12 and 14 (decimal) and store the fs! )! , { add la rger numbers.
Program to add numbers from the memory
result in the memory. .\
Here is a program to add two numbers stored in the memory. Compare the hex codes for
Machine code checklist the instructions in this program, which uses absolute addressing, with those for the
6. Fill in the addresses in the program- previous adding program which used immediate addressing.
1. Write your program in assembly
remember to put the two bytes in reverse
language and convert any data to hex. order. (See pages 18-19.) Z80program
2. Look up the hex code for each of the
mnemonics (there is a list of the Mnemonics Hex codes Meaning
mnemonics and hex codes at the back of Before running the hex loader, LD A, (address 11 3A, add ress 1 Put the number in address 1 into the accumulator.
the book). check the hex codes in the data line
very carefully. LD B.A 47 Put the number in the accumulator into registerB.
LD A, (address 21 3A, add ress 2 Put the number in address 2 into the accumulator.
Do n'tforgetto put END afte r you r ADD A,S 80 Add the number in register B to the accumulator.
list of hex codes in the hex loader. 7. Type in the hex loader (you could save
this program on tape) and fill in the hex LD (address 31, A 32, address 3 Store the contents of the accumulator in address 3.
codes in line 160 followed by the END RET C9 Return
signal. (See page 24.)
3. Add the return instruction to the end of To add two numbers from memory you straight from the memory, though, so you
the program. (See page 23.) have to load them into the registers first. For have to put the first number into A and then
this you can use the accumulator (A) and transfer ilia B.
4. Count up the number of bytes and If vour programs won't run, check
that vou have used the correct hex register B. You cannot load register B
reserve your free RAM area. (See pages
codes.
20-22.) 6502 program
Make a note of the addresses of 8. Run the hex loader and input the Mnemonics Hex codes Meaning
data bytes and of the address decimal address of the firstlocation LDA add ress 1 AD address 1 Put the number in address 1into the accumula~
where you have stored the where you wish to store the machine
program . ADC address 2 6D address 2 Add the number in address 2 to the accumulator.
code. (See page 25.)
STA add ress 3 8Daddress 3 Store the contents of the accumulator in address 3.
9. Run the machine code program using
your computer's command with the RTS 60 Return.
address (in decimal) of the first location
where the machine code is stored. (See Running the program
page 25.) To run 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. You should
If you change the data in the hex choose memory locations at the beginning of the area you have cleared for machine code, to
5. Work out what memory locations you loader you have to run the keep these data bytes separate from the instructions. Then convert the addresses to hex and
need for data bytes and convert the prog ra m aga in to poke the new insert them in the program. You need a third address for the answer. To see the result, type
26 addresses to hex. (See page 23.) bytes into th e memo ry. ,---~.Q~~:.... PRINT PEEK(address 3). 27
.
Working with big numbers
1I The carry flag
The programs on the previous few pages only work with numbers which add up to I The carry flag is a single bit in the flags
255 or less. This is the hIghest number that you can represent with the eight bitsin register (also called the processor
one register or memory location. To work with larger numbers you need to know a status register), which is used to
little more about the binary number system, and how to use the carry flag Overthe indicate when the answer to a sum is
page there is a machine code program to add larger numbers. greater than 255 and will not fit into one
Binary numbers byte (eight bits). Whenever this
The binary nwnber system works like hex and decimal nwnbers except that there are only
happens the computer automatically ¥oucan think of the carry flag as a ninth bit
two digits, 0 and 1. To make nwnbers biggerthan I you use several digits and the value of puts a I in the carry flag This is called indicating that a binary I has been carried
each digit depends on its position in the nwnber. setting the carry flag and making it 0 IS over from column eight of a nwnber. For
called clearing it. example, look at the sum 164 + 240
(l0 100 100+ 11110000 in binary), below.
111 1 1 1 r---~--~-.=-~~~----,
1 1 Decimal CARP:t Bina ry To add binary numbers you carry 1
each time a column totals more than
x 12 8 x 64 x3 2 x 16 x8 x4 x2 x1 128 64 32 16 8 4 2 1 1 just as you do in decimal addition
Ninth 1 o
164 00 1 00 when a column totals more than 9.
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 L-~'""'"-
+240 bit + 1 10000
In a binary nwnber, each digit has twice the third, the nwnber offours; the fourth the '1-1------------ ~_ " . ~, I
the value of the digit on its right. The first nwnber of eights and so on, as shown above. 404 ~ 0 0 101 00' ~~~~~~
digit (the one on the right) shows how To convert a binary nwnber to decimal you
many ones there are in the nwnber. The The answer to this sum is 404 which takes the computer it would be represented by
multiply each digit by the value of its position
second digit shows the nwnber of twos; up nine bits in binary. The ninth bit shows the bit in the carry flag.
in the nwnber and add up the answers.
how many 256s there are in the nwnber.ln
1[J) ~~JJ l l lf ( ~ 1 1 ~ ~
LO BC, (address XI ED 4B, address X Puts byte from address X (low order byte,
second number) into register C and byte from
~ This opcode is address XI (high order byte, second number)
two bytes long. into register B.
ADD HL,BC 09 Adds contents orRL and BC and leaves result in
HL. It does not add in the carry flag but it does set It stores the result in location Y (4th line). Then it adds the two Lines 8-10 check to
the carry flag if necessary. high order bytes and the carry (if there was one) from the see if the carry flag
Stores low order byte of answer in ad dress previous sum. It stores the result in location YI (7th line). was set using the same
LO (address VI, HL 22, address V Y and high order byte in address Yl. method as shown at
LO A,&O 3E,0 Seeing the result the top of the page.
See opposite page for how the (See oppos ite for The result is stored as three bytes. The low
ADC A,&O CE,O computer checks the carry flag. how to disp lay PRINT PEEK (Y) +«PEEK(Yl)
LD (addressZI,A 32 addressZ the resu lt of order byte (location Y) shows the number of *256)+(PEEK<Z)* 6»
this program. units. The high order byte (location Y I)
RET C9 Return. See if you can adaptthe program
shows the number of 256s. This time the carry
on page 27 so that it can cope w ith
To run the program you need to !ill in the specify one address for each pair. The (location Z) shows the number of 65536s. To results greater than 255. Hint: you
hex addresses for W, X, Y and Z. (Don't computer automatically puts the byte fromr~ • ~ see the result use the instruction shown on the need to add lines to check the carry
forget to reverse the pairs of digits.) When the next consecutive address into the other ~ right. (Replace Y, YI and Z with your fla . (Answer page 44.
30 you use the registers ill parrs you need only register ill the parr. computer's addresses.)
Displaying a message on the screen Z80 message program
The next program shows you how to use machine code to display a message on the Here are the mnemonics and hex codes for the Z80, Before you run the program, poke your
screen, The program for the 280 is on the opposite page and the one for the 6502 IS on message into free RAM, Then fill in the addresses in lines I and 2 of the program, Thelast
page 34, The two programs follow the same basIc principles, although the method is instruction of the program tells the computer to jump back to the third instruction,
slightly different for the different microprocessors, * You need to insert the address where the third instruction will be stored in your computer,
into the last line of the program,
Howthe program works
-'--'MO-::-e-ss-a-ge- l Mnemonics Hex codes
~i!:<:'.;;=~ This is immediate
t~~"f f?
LD lU;, screen address 21, screen address addressing - the operand is
[Ej - ,,-,- LD DE, message aaaress
LD A, (DE)
11, message address ] "1j!:t.:~l,~N\ the data to be loaded into
the registers.
~~~~~
lA
CP,&FF
_::J! I _ _, __, ==:lL---I
RETZ
LD (HL),A
FE FF
CB
77 In indirect addressing the
First you poke the character code for each of the message you poke in the code 255 as a INC, DE 13 operand is written in
letter of your message into locations at the signal to tell the computer thIS is the end of INC, HL 23 brackets.
JP, address of 3rd \ C3, address of 3rd
beginning of your free RAM area, Each the message, instruction mstructlon
letter takes up one byte, At the end
In this 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 instructions in
the third and sixth lines use indirect addressing,
In the 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 data is
fetched), into register pair DE,
~~mm~
Comparing things This is indirect addressing, Then it flag is 0, it carries on with the next
compares the byte in the accumulator with instruction.
G Zero flag ~ 0
~~
A200 figu re 07 tells the instruction the computer is to carry out. The computer reads the number in the program
LDX#&OO
counter and then goes to the location with that address to fetch its next instruction. Then the
",B Dmessage address
1.1)
LDA messaqe address, X computer how
/ CMP#&FF C9FF many locations to program counter is increased by one so it points to the next memory location.
BEQ to RTS instruction F007 ~ .~ ( iumptoreachthe
( STA screen address X 90 screen address
Ea ~
RTS instruction.
/'
INX
J MP address of 2nd instruction ~4C address of 2nd instruction
RTS "60
This program uses another addressing Y registers are added to the operand to give
mode, called "indexed addressing". In the address where the data is stored. The
When you tell the computer to jump or Jump
indexed addressing, the contents of the X or second and fifth lines use indexed addressing.
branch to a certain address, that address is sequence from that address. The opcodes
lo~m
put in the program counter and the for a jump on the zeo and 6502 are shown in
computer then carries out the instructions in the picture above.
Subroutines
The instruction "CALL address" on the zeo and "JSR address" (jump to subroutine) on the
In the first line, the computer puts 0 into the in the instruction. The result gives it
6502, tell the computer to go to a subroutine. This is just like in BASIC and at the end of the
X register. The second instruction uses the address of the data to be loaded into the
subroutine you need the return instruction (RET on the zeo and RTS on the 6502).
indexed addressing so the computer adds accumulator (a byte of message).
the contents of the X register to the address Seven bytes
CMP#&FF
72.. .II"-11~
~o
o
c=:n=cn
CMP in the third line makes the computer flag is I). In the hex codes it is followedbya
compare the byte in the accumulator with number telling the computer how many When you tell the computer to go to a instruction after CALL or JSR) are stored or
&FF (hex for 255), the signal for the end of locations to jump. We wantthe computer to subroutine, the address of the subroutine is "pushed" on the stack. The stack is a special
the message. If they are equal it sets the branch to RTS if the message byte equals put in the program counter. The contents of part of RAM set aside for the computer's use
zero flag to I. The next instruction,BEQ, 255 and there are seven bytes between the the program counter (the address ofthe (see page 10).
stands for "branch if equal" (i.e. if the zero branch instruction and RTS.
SCREE:N MEMORY
Next, in the fifth line, the program uses the X register. Then it jumps back to the
indexed addressing to store the byte in the second instruction. This time X is I, so it
accumulator (the message byte) at the loads the next byte of the message into the When the computer reaches the RTS or RET This is the address of the instruction after
address given in the instruction plus X. accumulator and stores it at the next screen instruction at the end of the subroutine, it the one which sent it to the subroutine. This
INX stands for "increment X" and it location. retrieves, or "pops", the last item off the is also what happens when you tell the
makes the computer add I to the contents of stack and puts it in the program counter. computer to run a machine code program. 35
Remember to count
Conditional branches Working out the displacement two bytes for an address.
In a conditional branch the computer tests one of the bits in the flags register and then, . When you give the computer a displacement number in a conditional branch, the
depending on the result, either branches or carries on with the next instruction. Here are the . computer works outthe address 6fthe instruction it is to jump to by adding or subtracting
bits in the flag register which you can test in conditionalbranches. the displacement from the program counter. To work outthe displacement, count the
number of bytes up to and including the instruction you want to jump 10. Start atthe
instruction after the conditional branch and count that as 0 (because the program counter
III NorS l& \::=!" &l r;;o
~ Y 1,11 ) c Q will already point to 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.)
1\1,-11\
~ r7I
( 0 ~ ).-
~ L I)" LDAaddress
CMP #&FF
Z This is the zero
?r 7t ~ flag and it is set to 1
if two pieces of data
BNEtoRTS
( STAaddress
are equal.
RTS STA tb hb RTS
V :..& il,,;l ~ IQ ~I IbO . To make the computer jump to the RTS In the example below, the displacement
" I
instruction in the example above, the to make the computer jump back to the
N or S This is the sign V or P IV This is called the overflow bit on the 6502. C This is the carry displacement is 3. ADC instruction is - 6
bit. It is referred to as N On the Z80 it has two functions and is called the flag. It is set to 1
on the 6502 and S on the parity/overflow. As an overflow bit it is set to 1 when whentheanswerto LDA #&OO
~F~
Z80. It is set to 1 when the result of a calculation in two's complement a sum will not fit in ADC#&01 -...ui
notation (see opposite) results in a carry over to the one byte.
~
the result of a
calculation is negative sign bit. ( CMP#&FF .
BNE to ADC Countlhis
and 0 for positive As a parity bit it is set to 1 if there is an odd nwnber RTS _ mstructIon
. results. of ones in a byte and is used for checking purposes . asO. LDA 00 ADC 01 CMP FF BNE RTS
Various instructions in addition to the on the 6502 the Instruction DEC Forwards and backwards jumps
compare instruction cause these flags to be (decrement) affects the sign and zero For forwards jumps you just translate the displacement into a hex number and insert it in the
automatically set or cleared. For example, flags .• program. For backwards jumps, though, the displacement is a negative number and there is
no way of indicating negative numbers in eight bit binary. Instead, you use a different system
Conditional branch opcodes of notation called "two's complement" . In two's complement, the left-hand bit is used as a
Here are the conditional branch instructions for testing each bit. sign bit. If this bit is 1 the number is negative. If it is 0 it is a positive number.
Z80 6502
Jump if •.. Branchif .•.
Two's comDh~mlerlt
JP C ................ there is a carry (C = 1). BCS ................ there is a carry (C = 1). 1. To work outthe two's complement of a
1285 645 325 165 8s 45 25 15
JP NC ...... ....... nocarry(C = 0) BCC ................ no carry (C = 0) number, say 6 (the displacement for the
6=00000110
JPZ ................ equal(Z = 1) BEQ ................ equal(Z = 1) program above), first write down the
JP NZ .............. notequal(Z = 0) BNE ................ not equal (Z = 0) number in binary.
JP M ............... minus(S = 1) BMI. .............. .. minus (N = 1) 1 1 0 0
2. Then you change all the Os to I and the Is
JP P ................ plus(S = 0) BPL. ................ plus (N = 0) to O. This is called "flipping the bits" or 1 and 1 make
JPPO .............. parityodd(PN= 1) BVS ................ overflow set (V = 1) IIcomplementing" a number. The result is Ocarry1.
JP PE ............ .. parity even (PN = 0) BVC ................ overflow clear (V = 0) 111111
called the "one's
~o
~JB-,o
complement".
(
:;:, 3. Next add I. The
r- JP C addressJRNC&05 ~ zao
Jump Slocations if I:;\~ BCS &05 result is the two's
This is the two's
complement of 6.
111010
zao ~
ID ~
number.
8s 45 25 15 8s 45 25 15
~
6502 6502 4. Now you need to convert this to hex to
Jump to a certain 1 1 1 1 l' 0 1 0
address if there is a Branch 5 locations if
there is a carry.
Branch 5 locations if
equal.
r insert it in the program. The easiest way to
do this is to divide the number down the = decimal 15 = decimal 10
~ ~
carry.
le ~
.~
~
middle and work out the decimal and then = hexF =hexA
After the "JP test" instruction on the Z80 you addressing" and the number is called the the hex value of
give the computer the address of the "displacement", or "offset".
So the hex representation of the two's backwards displacement you can have.
instruction you want it to jump to. On the The zao has an additional conditional complement of 6 is FA and for a backwards The biggest forwards displacement is 127,
6502 you give the computer a number which branch instruction, "JR test", which you use jump you insert this number in the program. the highest number you can make with the
tells it how many locations it has to jump with a displacement rather than an address. In two's complement, the highest number eighth binary digit set to 0 to indicate a
forwards or backwards to find the JR stands for "jump relative" and you can only
you can represent is 128. This is the bigge:..st:r-~p-=.O::.Si:::ti:::v-=.e-=.n:::umb_~.e_r_._ _ _ _ _ _ _ _ _,
.instruction. This is called "relative test the zero flag and the carry flag withJR. 37
,.. A complete list of your microprocessor's instruction set will tell you which instructions affect which ---=----~...:: Can you wo rk out th e hex forthe two's
flags. ~ complement of12, 18 and 9 7 IAnswer page48)
Screen flash program 6502 screen flash
This program swaps the two blocks, byte by byte (i.e. character by character), starting
On these two pages there is a program which swaps two blocks of display on the with the last byte in e~ch block. It loads these bytes into the registers, then stores the byte
screen to make a flashing effect. It shows how simple animation works. The from block a in the screen location for block b and vice versa. Then the program is
program for the Z80 is given below and the one for the 6502 is on the opposite page.
:ep:~~~:~~~~~~~~~:~~~~~~~~~~~. ~* R COUN~A~XT.~ER ~
At the end there are guidelines for runnmg the program for both micro processors.
zao 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
b 00000000000000000000000000000000 ~ . _ _ . __
00000000000000000000000000000000
block a and vice versa. IaI:<JI:<J ca Ir!:8IBI23
********************************
L2 L2':=tr§1-----:J
**********************.*********
Block a
00000000000000000000000000000000 It uses indexed addressing to find the staning address for each block. The
00000000000000000000000000000000 Blockb
address for each byte. The total number of instruction DEX (decrement X) makes the
ADDRESS b
bytes in one block is loaded into the X computer subtract 1 from X so that, when
register. Then, to store or load a byte, the the program repeats, the computer fetches
ADORESS a. number in the X register is added to the the next byte back in the display.
The program uses indirect addressing. The the program repeats, these are the 6502 screen flash program
screen addresses for the first byte of each addresses of the next two bytes in each See the bottom ofthe opposite page for how to work out the values of n, a and b. Then
block are stored in registers HL and DE. block on the screen. subtract I from a and b so that when the computer adds X it gets the last address in each
The computer reads the addresses in these Register B holds the number of bytes to block, rather than the first address of the next line. (Make sure n, a and b are in hex.)
registers each time it loads or stores the be swapped. Each time the program
Mnemonics Hex codes M eaninll
bytes. After swapping two bytes the repeats, B is decremented (decreased) by I
instruction INC (mnemonic for increment) so it acts as a counter. WhenB = Oall the LOX#n A2n Load X with the number of bytes in one block.
makes it add one to HL and DE so that when bytes have been swapped. LOA address a, X BD address a Put contents of location with address a + X into accumulator.
TAY A8 Transfer contents of accumulator to register Y.
zao program jg LOA address b, X BOaddressb Put contents of location with address b + X into accumulator.
n = number of bytes in one block; a = first address of block a; b = first address of block b. STA address a, X 90 address a Store contents of accumulator at address a + X.
~ TYA 98 Transfer contents of Y register back to accumulator.
Meaning
~
Mnemonics Hex codes (H L holds address
for block a and \- STA address b, X 90 addressb Store contents of accumulator at address b+ X.
LOB,n 06,n Counter.
) DE ho lds address OEX CA Decrement X. Zero flag is set to I when X O.
LO HL, (address a)
LO DE, (addressbl
21 , address a Put address of block a in HL.
11 , address b Put address of block b in DE.
for block b. "I-- ~ B N E to instruction two DOEF Branch back &EF locations if X is not equal to o. EF is the
hex for two's complement of 17 (see page 37).
LDC,(HL) 4E Load C with contents of address in HL (indirect addressing).
RTS 60 Return
LO A,(OE) lA Load A with contents of address in DE (indirect addressing). "-
LD(HL).A 77 Store contents of accumulator at address in HL (indirect).
LOA,C 79 Put C (first byte block a) into accumulator. Loading and running the program for the zao or 6502
LO(OE).A 12 Store contents of accumulator at address in DE. The best way to run this program is as a 3. Next, add the following lines to the end
INCHL 23 Add one to HL and DE. 'machine code subroutine in the hex of the program:
INCOE 13 loader. To do this, follow these steps: 240 CALL 8ddress where machi ne
OECB 05 DecrementB, the counter. 1. Type in the hex loader and put the hex cod e i s s tor ed
250 FOR K=l TO 500
LOA,&OO 3E.00 Put 0 in the accumulator codes for your computer's 260 NEXT K Change figure 500 indelay
CPB B8 Compare B with contents of the accumulator (0). microprocessor in line 160. 270 BDTO 240 loop to suit your computer.
If Bdoes not equal zero, jump back &F310cations to load 2. At line 180 you need two loops to poke 4. Now type RUN to run the program. The
JR NZ to 4th instruction 20,F3 next bytes into registers. F3 is hex for two's complement the characters for the display into the hex loader pokes the hex codes into the
ofl3 (see page 31). screen memory. For example, here are memory, then pokes the display codes
RET C9 Return. the lines for two rows of * s (code 42) into the screen memory. Line 240 makes'
followed by two rows olOs (code 48), for a go to the location where the machine c
Filling in the data and addresses computer with a 40 column screen. program is stored and carry out the
addresses a and b If you want to swap the top two instructions. By itself, the machine code
n (number of characters in
lines of the screen with the next two lines, make 180 FOR J=O TO 79 program only swaps the display once, so
one block) To find n, multipl 190 POKE first screen address + J. 42 line 270 makes it call the program again
the number of characters in address a the first address of your computer's screen 200 NEXT J
memory. Address b is the address for block a plus the 210 FOR J=80 TO 159 and again to make a flashing effect. You
a line by the number of lines
220 POKE first screen address + J~48 need the delay loop because the machine 39
in one block. Convert to hex. number of bytes to be swapped. Convert both
230 NEXT J code is so fast.
addresses to hex.
Going further Decimal/hex conversion charts
[f you want to find out more about machine code the best way is to try writing your Thls chart converts hex numbers from 0 to Ft to decimal and vice versa.
own short programs and to test and study pr ograms wri tten by other people. One Hex to decimal Decimal to hex
good way to use machine code is as a short subroutine to carry out a particular task To convert a hex number to decimal read To convert a decimal number to hex, find
in a BASIC program. For instance, machine code is particularly suitable for sorting along the row for the first hex digit in your hex the decimal number in the chart. Then read
data or filling the screen with graphics because it is faster and takes less memory number and down the column for the second back along the row for the first hex digit and
space than BASIC. You can find subroutines for dOing thi ngs like this in magazines. hex digit. The number where the row and up the column for the second hex digit e.g .
If the subroutines are written specially for your computer you can run them without column meet is the decimal equivalent for 154 is 9A.
alteration. If they are written for another make of computer which uses thesame your hex munber, e.g. hex Al is decimal 161.
microprocessor you will need to change any addresses in the program for
Second hex digit
addresses in the area in your computer's memory that you have chosen to store
0 1 2 3 4 5 6 7 8 9 A B C 0 E F
machine code.
0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Using an assembler 1 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Machine code subroutines 2 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
Here are the steps you need to follow to use An assembler (a program which enables 3 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
a machine code subroutine in a BASIC you to type in a machine code program in 4 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
program. mnemonics) makes machine code .t: 5 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
Cl 6 96 97 98 99 100 101 102 103 104 105 106 107 108 109 11 0 111
1. Make room in the memory for the programming much easier. You can buy '6
machine code by lowering the top of user )( 7 11 2 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
an assembler on cassette for most home
RAM (see pages 20-22). computers and some, such as the BBC, •"
~
8
9
128
144
129
145
130
146
131
147
132
148
133
149
134 135 136 137
150 151 152 153
138
154
139
155
140
156
141
157
142
158
143
159
2. Put the codes for the machine code have a built-in assembler. i!! 161
i.: A 160 162 163 164 165 166 167 168 .169 170 171 172 173 174 175
subroutine into line 160 of the hex loader With an assembler you can type in B 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
program on page 24. (Make sure there is a comments alongside the mnemonics to C 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
return instruction at the end of the machine remind you what each line does. The 0 208 209 210 21 1 212 213 214 215 216 217 218 219 220 221 222 223
code program.) Add lines to poke in any assembler will then display the program E 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
data bytes if necessary, then type in and run on the screen in hex and mnemonics, with F 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
the hex loader. the addresses where the instructions are
3. Number your BASIC program using line Converting addresses
stored and the comments. To use the chart to convert hex addresses, equivalent for the second pair of digits to
numbers starting after those used in the hex The assembler will automatically
loader. At the point where you want the look up the decimal equivalent for the first find the position on the page. Multiply the
reverse the pairs of digits in addresses pair of digits in the address. This is the page page number by 256 and add the position
computer to carry out the machine code, and work out the address or displacement
put your computer's command for running a number. Then look up the decimal on the page.
for a jump. Some assemblers allow you to
machine code program as a line in the use symbolic names for data, like .,
BASIC program. variables in BASIC. A good assembler
Two's complement conversion chart
This tells the also has a debugger to find mistakes and This chart gives the two's complement in find the number in the chart, then read
computer to go to
B an editor to help you correct them. hex of decimal numbers from -I to -128. along the row for the first hex digit and up
location 16002 and
'a ""1S /C To convert a number to two's complement, the column for the second digit.
carry out the <0 ~~ Suggested books
instructions there.
30~ Second hex digit
s~o~
There are lots of books on machine code F E 0 C B A 9 8 7 6 5 4 3 2 1 0
specially written for one partiCu!ar make of .t: F 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
6c c"'I£.<.. ~ microcomputer. The best way to choose Cl
'6
E 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
one is to read the reviews in computer 0 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
;tc ~. - 1"00 )(
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
"'-c.,. ~ -< magazines. You may also find the following
books useful:
•"
~
C
B 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
4. Type the BASIC program into your
Programming the Z80 and Programming "
~
i.:
A 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
computer and then type RUN. The 9 97 98 99 100 101 102 103 104 105 106 107 108 109 110 11 1 112
computer will carry out the BASIC the 6502, both by Rodney Zaks and 8 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
instructions and when it reaches the line published by Sybex. These are very
telling it to run the machine code program it detailed guides with complete lists of all the Doing conversions on a calculator To convert the remainder to a whole
will go to the address where the machine instructions for each microprocessor. They When you do conversions on a calculator number you subtract the number before the
code is stored and carry out the are not easy to read for beginners, but they the calculator displays the remainder as a decimal point, then multiply by the number
instructions. The return instruction at the are useful for reference. decimal number. For example, if you are you divided by.
end of the machine code will send the VIC 20 Programmer's Reference Guide converting decimal 134 to hex you divide by
published by Commodore. 8.375 - 8= 0.375 x 16 = 6
computer back to the next line in the BASIC 16 then convert the answer and remainder 41
program. 6502 Machine Code for Beginners by A. P. to hex digits. A calculator would give you So 134 .,. 16 = 8 remainder 6 therefore
Stephenson, Newnes Microcomputer Books. the answer as 8.375. decimal 134 is 86 in hex.
Z80 mnemonics and hex codes JP (rr)Jump to address held in lID A, (x) Load accumulator LD E,r Load register E with
register pair IT. (Implicit '. with contents of address x. the contents of register r.
The mnemonics and hex codes for the instructions covered in this book are givenon addressing.) (Absolute addressing.) (Implicit addressing.)
the next few pages. The term "impllcit addressing" used in these llsts is just the name LD E,A 5F
JP(HLI E9 LDA,(xl 3A,(xl
for instructions where no operand need be specified in the hex code. There are a JP (lXI LDE,B 58
DDE9
few other instructions not llsted here and if you want to go further with machme code JP (lYI FDE9 LD n, (x) Load register pair IT LDE,C 59
you will need a complete llst of the Z80 instruction set (see page 40). The following with contents of addresses x LDE,D 5A
abbreviahons are used in these llsts: JP c,x Jump to address x and x+ 1. (Absolute LD E,E 5B
addreSSing.)
n = number rr = register pair c = condition depending on condition c. LDE,H 5C
nn = two byte number x = address d = displacement c maybe Z (equal); NZ (not LD E,L 5D
LD BC, (xl ED4B,(xl
equal); C (carry); NC (no
r = register carry); PE (parity even); PO
LD DE, (xl ED5B,(xl LD H,r Load register H with
(parity odd); M (minus) or P LD HL, (xl 2A,(xl the contents of register r.
ADC A,D Add with carry, a CALL x Go to subroutine DEe r Decrement register r. (Implicit addressing.)
(plus). (Immediate
number, n, to the accumulator. starting at address x. (Implicit addressing.) LD A,r Load the accumulator
addressing. ) LDH A 67
(Immediate addressing.) (Immediate addressing.) with contents of register r.
DECA 3D LDH,B 60
CALLx CDx JPZ,x CA,x (Implicit addressing.)
ADCA,n CE,n DECB 05 LDH,C 61
JP NZ,x C2,x
CALL c,X Go to subroutine DECC OD LDA,A 7F LDH,D 62
ADC A,r Add with carry, JPC,x DA,x
starting at address x DECD 15 LDA B 78 LDH,E 63
register r to the accumulator. JP NC.x D2,x
depending on condition c. DECE 1D LDA,C 79 LDH ,H 64
(Implicit addressing.) JP PE,x EA,x
cmaybe Z(equal); NZ (not DECH 25 LDA,D 7A 65
JP PO,x E2,x LDH,L
ADCA,A 8F equal); C (carry);NC (no DECL 2D LDA,E 7B
carry); PE (parity even); PO JPM,x FA,x LD L,r Load register L with the
ADCA,B 88 LDA,H 7C
(parity odd); M (minus) or P DEe rr Decrement register JPP,x F2,x contents of register r. (Implicit
ADCAC 89 LDA,L 7D
(plus). (Immediate pair IT. (Implicit addressing.) addressing.)
ADCA,D 8A
addressing.) DECBC OB
JR d Jump relative. Jump d
ADCA,E 8B LD B,r Load register B with LD L,A 6F
bytes (the displacement).
ADCA,H 8C CALLZ,x CC,x DECDE 1B the contents of register r. LDL,B 68
(Relative addressing.)
ADCA,L 8D CALLNZ,x C4,x DECHL 2B (Implicit addressing.) LDL,C 69
CALL C,x DC,x DEC IX DD2B JRd 18 d LDL,D 6A
LDB,A 47
ADC HL,rr Add with carry, CALLNC,x D4,x DECIY FD2B LD L,E 6B
the contents of register pair IT JR c,d Jump relative. Jump d LDB,B 40
CALL PE,x EC,x LDL,H 6C
to HL. (Implicit addressing.) DEC (HL) Decrement bytes (the displacement) LDB,C 41
CALLPO,x E4,x contents of address held in HL. LD L,L 6D
depending on condition c. LDB,D 42
ADCHL,BC ED4A CALLM,x FC,x (Indirect addressing.) c may be NZ (not equal); Z LDB,E 43 LD r, (n) Load register r with
ADC HL,DE ED5A CALLP,x F4,x (equal); NC (no carry) arC
DEC (HLI 35 LDB,H 44 contents of address held in
ADC HL,HL ED6A CCF Complement carry flag. (carry). (Relative addressing.) LDB,L 45 register pair IT. (Indirect
(Implicit addressing.) INe r Increment register r. addressing.)
ADDA,D Addanumber,n,to (Implicit addressing.) JR NZ,d 20,d
the accumulator. (Immediate CCF 3F LD C,r Load register C with LOA, (BCI OA
JRZ,d 28, d
addressing.) INCA 3C the contents of register r. 1A
CP n Compare contents of JR NC,d 30,d LDA,(DEI
INCB 04 (Implicit addressing.)
accumulator with data n . JRC,d 38,d LDA,(HL) 7E
ADD,n C6,n INCC OC
(Immediate addressing.) LDC,A 4F LD B,(HLI 46
ADD A,r Add register r to the INCD 14 LD r,n Load register r with LD C,(HL) 4E
CPn FE n LDC,B 48
accumulator. (Implicit INCE 1C data n. (Immediate 56
LDC,C 49 LD D,(HLI
addressing.) CP r Compare contents of INCH 24 addressing.) 5E
LDC,D 4A LDE,(HLI
register r with the accumulator. INCL 2C 66
ADDA,A 87 LDA,n 3E,n LDC,E 4B LD H,(HLI
(Implicit addressing.)
ADDA,B 80 INC n Increment register pair LDB,n 06,n LDC,)-I 4C LD L,(HL) 6E
CPA BF'
ADOA,C 81
B8
IT. (Implicit addressing.)
- LDC,n OE,n LDC,L 4D LD (x),A Store the contents of
CPB INCBC 03 LOO,n 16,n
ADDA,D 82 the accumulator in address x.
CPC B9 INCDE 13 LD D,r Load register D with (Absolute addressing.)
ADDA,E 83 LDE,n 1E,n
CPD BA INCHL the contents of register r.
ADDA,H 84 23 LD H n 26,n 32,x
CPE BB (Implicit addressing.) LD (xl,A
ADDA,L 85 INC (HL) Increment contents LD L,n 2E,n
CPH BC LD (x),rr Store the contents of
of address held in HL. (Indirect LDD,A 57
ADD HL,rr Add the contents CP L BD LD rr,nn Load register pair rr register pair IT at addresses x
addressing.) LDD,B 50
of register pair IT to HL. with two byte number nn. and x + 1. (Absolute
CP (UL) Compare contents of LDD,C 51
(Implicit addressing.) INC(HLI 34 (Immediate addressing.) addressing.)
accumulator with contents of LDD,D 52
ADD HL,BC 09 address held in HL. (Indirect JP xJump to address x. LD BC,nn 01,nn LDD,E 53 LD( xl,BC ED43,x
ADD HL,DE 19 addressing.) (Immediate addressing.) LD DE,nn 11,nn LDD,H 54 LD (xI,DE ED53, x 43
ADD HL,HL 29 CP(HLI BE JPx C3x LD HL,nn 21,nn LDD,L 55 LD (xI,HL 22,x
LD (rr),r Store the contents of RETC D8 SBC A,(HL) Subtract with 6502 mnemonics and hex codes
register r at the address held in RETNC DO carry the contents of address
register pair IT. (Indirect RETPE E8 held in register pair ill, from This chart shows the mnemonics and hex codes for all the instructions (plus a few
addressing.) RETPO EO the accumulator. (Indirect more) covered in this book. The mnemonic instructions are given down the left and
LD(BC)A 02 RETM F8 addressing). the hex codes for each instruction in the different addressing modes are shown
LD(DE)A 12 RETP Fa SBCA,(HL) 9E across the chart. Zero page addressing is just like absolute addressing, i. e . the
LD (HL)A 77 SCF Set carry flag. (implicit
operand is the address where the data is stored, but the address must be in page
LD(HLI,B 70 SBC A,n Subtract with carry zero (i. e. locations 0-255) ofthe memory (see page la). Implied addressing is just the
data n from the accumulator. addressing.)
LD(HLI,C 71 term used to describe instructions where no operand need be specified, e. g. CLC.
(Immediate addressing.) SCF 37
LD(HLI,D 72 There are a number of other instructions not given here, and if you want to go further
LD (HL),E 73 SBCA,n DE,n SUB n Subtract data n from the with machine code you will need to get a complete list of the 6502 instructionset.
LD (HL),H 74 accumulator. (Immediate
LD (HL),L 75 SBC A,r Subtract with carry addressing.)
contents of register r from the SUB,n D6,n
LD(rr),n Storedatanat accumulator. (Implicit
address held in register pair IT. addressing.) SUB r Subtract contents of
(Immediate/indirect .'J ~
>< >-
register r from the .,!? .'J en
a..•
~
addressing.) SBCAA 9F accumulator. (Immediate
Addressing mode
"E
~
~
"
~
""
~
"
.,,! >
'"•
LD (HL),n 36 SBCA,B
SBCA,C
98
99
addressing.)
§ «"
.0 " E'
~ "
~
~
.E "
~
.E §
0. 0;
er
RET Return from subroutine. SUBA 97
SBCA,D 9A
(Indirect addressing.) SUBB 90 Data Any Address Address None
SBCA,E 9B 0 perand is address in page + x +y ment
SUBC 91
RET C9 SBCA,H 9C zero register register
SUBD 92
RET c Retwn from subroutine SBCA,L 9D ADC plus the 69 6D 65 7D 79
SUBE 93
depending on condition c. SUBH 94
ccanbe Z (equal); NZ (not SBC HL,rr Subtract with carry
SUBL 95 Notethat not all the in structions can
equal); C (carry); NC (no contents of register pair IT from
be used in all the addressing modes.
carry); PE (parity even); PO register pair ill. (Implicit SUB (HL) Subtract the
(parity odd); P (plus); M addressing.) contents of address held in HL
(minus). (Indirect addressing.) SBCHL,BC ED42 from the accumulator. (Indirect
addressing.)
RETZ C8 SBC HL,DE ED52
RETNZ CO SBC HL,HL ED62 SUB (HL) 96
.~ ~ ~
Puzzle answers
Page 11 ~="""';;;;';;;'~ZdY
complement of a number to subtract It 15
&A7in decimal IS 167. 513 mhexis &201 from 256, then convert the answer to hex.
Page26 (subtract I frorn) memory
1. 25+ 73 (25 is &19 and 73 is &49)
E.g.~=25~his~e~
zao 6502
Meaning
Mnemonics Hex codes Mne Hex codes
LDA,&19 3E,I9 LDA#&19 A919 Put&19 in accumulator.
ADDA,&49 C6,49 ADC #&49 6949 Add &49 to accumulator.
Store contents of
LD (address), A 32, address STAaddress 8Daddress accumulator at a-certain
address .
RET C9 RTS 60 Return
Computer and Video Games All about electronic games arid how they work,
with expert's tips on howto w in. 'The idea l book to convert the arcade games
freak to rea l computing."Computing Today .
Machine Code for Beginners A really simple introduction to machine code for
the Z80 and 6502.
Inside the Chip Asimple and colourful account of how the chip works and what
itcan do.
+001·99
ISBN 0-86020-735-8