(This is the second part of this intro to machine code programming series. See also last month’s column and Computer Number Systems, Feb.81 p.10, for more on binary numbers.–AZ)
The point to learning how to add and subtract binary numbers is to see how “carries” are generated and what happens to those extra digits.
In binary, answers to arithmetic operations are the same as in decimal; they just look different. For example, in decimal, 1+1=2. In binary, 1+1=10 (or 2 in decimal). The first digit, 1, is the carry. Addition is straightforward; just remember that 0+0=0, 1+0=1, 1+1=10 (or 0 and carry), 1+1+carry=1 and carry:
10001101 = 141 00110101 = 53 +00110010 = 50 +01011011 = 91 10111111 = 191 10010000 = 144
The largest number you can represent in binary with 8 bits is 255. To get an answer greater than 255, the Z80 (the central processor, or CPU, in your ZX80/81) has a 9th bit available to the Accumulator (where all bit manipulation takes place): the Carry bit in the Flags register. Disregarding just how the carry is transferred to the high order byte, this is generally how large numbers are saved in 2 bytes or addresses:
HIGH ORDER (2nd) LOW ORDER (1st)
00000000 10010111 = 151
+00000001<- Carry<- +10101000 = 168
00000001 = 256 00111111 = 63
256+63 = 319
The low order byte is the first of the two addresses; the high order byte is the second. See last month’s column for details.
Subtraction is a little trickier. Let’s subtract 45 from 152: First, the Z80 “inverts” 45, or changes all the zeros to ones and ones to zeros (00101101–. 11010010). It then adds 1, giving 11010011, which is 211 in decimal. This is the two’s complement of 45. This conversion to two’s complement explains why if you POKE -45, then PEEK that location, you get 211.
Next, the Z80 adds 211 to 152:
10011000 = 152 +11010011 = -45 or 211 01101011 = 107 (ignore the carry)
The correct answer is 107.
Depending on the results of addition and “subtraction” (conversion to two’s complement followed by addition), certain flags in the Accumulator-Flags “register-pair” will be changed.
NEXT MONTH: THE FLAGS REGISTER