Addition and subtraction with 6502 processor
I would like to share what I have learnt in my SPO600 course regarding addition and subtraction with 6502 processor.
In the processor status register, there is a "carry" flag, which take important role in the addition and subtraction. Each memory is 1 byte in 6502 processor. In the calculation of more than one byte, there could be a value carry over the next byte.
Addition
Example: If we add $0001 to $01FF, we first their low bytes, $01 and $FF. Result is $00 and the carry flag will be set. Then, we add the high bytes $00 and $01, then add the carry flag which is 1. The result will be $0200.
When we do the addition, other than the STA and LDA, some useful instructions are CLC and ADC.
ADC is the instruction which use to add the memory value to the accumulator. One important point is that if the carry flag is set, the result will add 1 extra. Also, if the result overflow, it will set the carry flag. For example, if the accumulator's value is $00 and we add #$01 to it with carry flag on, result will be $02.
In order to do addition regardless of the carry flag status, we can use CLC to clear the carry flag before the addition.
example code of adding #$04FF to #$0202 as below:
LDA #$02
STA $04
LDA #$02
STA $05
LDA #$FF
CLC ;clear carry flag before the low byte addition
ADC $04
STA $04
LDA $05
ADC #$04 ;DO NOT clear carry flag before the low byte addition
STA $05
Subtraction
In subtraction, sometime we have to borrow a digit from the high byte for the low byte subtraction. The subtraction instruction is SBC. What SBC actually do is that it deduct the accumulator's value by the memory value and if the carry flag is 0, it will deduct 1 extra. Also, if the subtraction need to borrow value from high byte, it will clear the carry flag. To perform subtraction, we also need another instruction SEC to set the carry flag, to ensure the subtraction is regardless of the status of carry flag.
Example: if we want to subtract $03FF from $0501,
1. we first set the carry flag,
2. subtraction of low bytes: deduct #$FF from $01. after this SBC instruction, the carry flag is now 0. and result is $02
3. subtraction of high bytes: deduct #03 from $05, since the carry flag was unset, the result is $01.
the overall result is $0102.
code as below.
LDA #$01
STA $04
LDA #$05
STA $05
LDA $04
SEC ;set carry flag ON before low byte subtraction
SBC #$FF
STA $04
LDA $05
SBC #$03 ;DO NOT act on carry flag before high byte subtraction
STA $05
Comments
Post a Comment