"...and then the different branches of Arithmetic - Ambition, Distraction, Uglification, and Derision." - Lewis Carroll, 'Alice's Adventures in Wonderland'
Created: 4th October 1999
Last Modified: 27th November 1999
This page explains the ADD and SUB instructions.
This instruction is fairly simple - it adds two things together. But there are a few
limitations and some interesting effects. We'll start with the general form:
add [register],[value_to_add].This adds [value_to_add] to
[register] and stores the result in [register]. However, [register] must be either
a or hl. If [register] is hl, [value_to_add] must be
bc, de or hl. So the following are allowed:
Sample_ADD_Instructions:
ld a,5
ld b,6
add a,b
add a,$12
ld c,3
add a,c
add a,a
ld hl,$fc00
ld de,12
add hl,de
But the following aren't:
Illegal_ADD_Instructions: ld b,7 ld c,9 add b,c ; First argument must be a ld a,5 ld hl,12 add a,hl ; Can't use a single register with a pair ld de,$1234 ld bc,$0123 add bc,de ; First argument must be hl
But what happens in the following example?
Strange_ADD_Code:
ld a,250
ld b,100
add a,b
250 + 100 = 350, but the maximum value for the a register is 255. Using an emulator (that's a complicated tool that isn't really necessary) we can see that the a register contains the number 94 after the program has been run. The number 94 is in fact 350 mod 256 (divide and take the remainder). That way there can never be a number larger than 255 in any 8 bit register. But how do we know if there has been an 'overflow'? The answer is the f (flags) register. If there was indeed an overflow then the carry flag would have been set. This will be explained later.
This instruction is just as simple - it is used for subtraction. The general form is
sub a,[value_to_sub], and it makes a become a - [value_to_sub].
Only the a register is allowed as the first argument.