Basic Arithmetic - Jimmer1/Chip16 GitHub Wiki
A computer is little more than a paperweight if it cannot perform computation. Chip16 offers 4 different opcodes to perform basic arithmetic. As alluded to previously, Chip16 can only perform computation on values in registers.
There are 4 opcodes which encode various addition and subtraction operations, these are:
Mnemonic - Opcode - Description
- ADD - 8XY4 - Adds register Y to register X and stores the result in register X.
- ADC - 7XNN - Adds 8-bit value NN to register X and stores the result in register X.
- SUB - 8XY5 - Subtracts register Y from register X and stores the result in register X.
- RSUB - 8XY7 - Subtracts register X from register Y and stores the result in register X.
All of these operations except ADC modify r15 as well which is designated the flag register. While it is possible to use r15 as a general purpose register, it is discouraged as many fundamental operations modify it.
The ADD opcode sets r15 to 1 if a carry is generated and 0 otherwise. This can be explained as follows:
Imagine you have a theoretical computer which can only store single decimal digits. So 1 + 1 = 2 and 5 + 4 = 9. Now consider the result of 5 + 5; 5 + 5 = 10 normally, but our theoretical computer can only store a single decimal digit. So our theoretical computer would record 5 + 5 = 0 which is mathematically incorrect but can be worked around by adding a carry flag to our theoretical computer so we have 5 + 5 = 0 and 1 carry to tell the programmer to account for the carry.
The SUB and RSUB opcodes set r15 to 0 if a borrow is generated and 1 otherwise. This can be explained as follows:
Imagine you have a theoretical computer similar to the one we thought up earlier, but it can only store single decimal digits bigger than zero. So 2 - 1 = 1 and 9 - 7 = 2. Now consider the result of 1 - 2; 1 - 2 = -1 normally but we can only store single digits bigger than 0, so in this case 1 - 2 = 9 as most computers and indeed Chip16 use a system where if the result of a mathematical operation becomes bigger than or smaller than the maximum or minimum value the register can store then the register wraps around. 1 - 2 = 9 is mathematically incorrect but can be worked around by setting a borrow flag to tell the programmer to account for the borrow.
Thanks are extended to Matt Godbolt for coming up with the idea of the theoretical single digit computer and for explaining the concept of a carry in the following Computerphile YouTube video: How CPUs Do Math(s) - Computerphile
I shall demonstrate the use of these opcodes as follows:
ADD
code = [
0x84, 0x14 # add r4, r1 # r4 += r1
]
ADC
code = [
0x78, 0x2a # adc r8, 0x2a # r8 += 0x2A
]
SUB
code = [
0x8A, 0xE5 # sub r10, r14 # r10 -= r14
]
RSUB
code = [
0x80, 0xD7 # rsub r0, r13 # r0 = r13 - r0
]
While extremely limited, these operations form the backbone of all computation on the Chip16.
Next: Bitwise Arithmetic