Memory allocation: Difference between revisions

m
(Added ZX81 BASIC)
Line 1,256:
 
The second approach, suitable especially if you want to reserve a few bytes for a small machine code subroutine, is to hide the storage space you want inside a comment. When you enter a <code>REM</code> statement, the interpreter sets aside sufficient bytes to store the text of your comment <i>and then doesn't care what you put in them</i>: if you know the address where the comment is stored, therefore, you can <code>POKE</code> whatever values you like into that space. If the comment is the first line in the program, the <code>REM</code> itself will be at address 16513 and the comment text will begin at 16514 and take up one byte per character. An example, with a trivial machine code routine (it adds 3 and 4):
<lang basic>10 REM ABCDEFGHIABCDEFGH
20 LET P$="3E030E04814F0600C93E03010400814FC9"
30 LET ADDR=16514
40 POKE ADDR,CODE P$*16+CODE P$(2)-476
Line 1,265:
80 CLEAR
90 PRINT USR 16514</lang>
The <tt>ABCDEFGHIABCDEFGH</tt> is arbitrary: any other nineeight characters would work just as well. The string in line <tt>20</tt> is the hex representation of the Z80 code, which could be disassembled as:
<lang z80asm>3e 03 ld a, 3
0e01 04 00 ld cbc, 40004
81 add a, c
4f ld c, a
06 00 ld b, 0
c9 ret</lang>
Line <tt>40</tt> reads a two-digit hex number and pokes its value into memory. <code>USR</code> ("user sub routine"), in line <tt>90</tt>, is a function that takes the address of a machine language routine, calls it, and returns the contents of the <tt>BC</tt> register pair when the routine terminates. Under normal circumstances, once you were satisfied the machine code program was working correctly you would remove lines <tt>20</tt> to <tt>80</tt>, leaving just the machine code subroutine and the call to it. Note that if you list the program once you have run it, the first line will look something like this:
<lang basic>10 REM Y▀Y▀▀:▖▟?▞ ▟?TAN</lang>
Unfortunately, you cannot type that in directly: not all 256 possible values are accessible from the keyboard, so there is no point trying to learn to enter machine code in that form.
 
519

edits