base:signed_8bit_16bit_addition
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
base:signed_8bit_16bit_addition [2015-04-17 04:33] – external edit 127.0.0.1 | base:signed_8bit_16bit_addition [2018-09-28 03:58] – white_flame | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | To add a signed 8-bit delta to a 16-bit value, we need to sign-extend the delta to a full 16 bits. | + | To add a signed 8-bit delta to a 16-bit value, we need to sign-extend the delta to a full 16 bits. |
- | < | + | Using only the accumulator: |
- | ldx #$00 ; implied | + | < |
+ | ; Standard low byte addition | ||
+ | clc | ||
+ | lda delta | ||
+ | adc value | ||
+ | sta value | ||
+ | |||
+ | ; Sign extend the high byte | ||
+ | lda delta | ||
+ | and #$80 ; Extract the sign bit | ||
+ | beq :+ ; If zero, add #$00 (+ carry) | ||
+ | lda #$ff ; Else, add $ff (+ carry) | ||
+ | :adc value+1 | ||
+ | sta value+1 | ||
+ | </ | ||
+ | |||
+ | The following version is 2 bytes shorter & 2 cycles faster, using .X: | ||
+ | |||
+ | <code 6502tasm> | ||
+ | ; Precalculate the sign-extended | ||
+ | ldx #$00 | ||
lda delta | lda delta | ||
bpl :+ | bpl :+ | ||
- | dex ; high byte becomes | + | dex ; decrement |
- | :clc | + | : |
- | adc value ; normal | + | |
+ | ; Normal | ||
+ | clc | ||
+ | adc value ; .A still holds delta | ||
sta value | sta value | ||
- | txa | + | |
adc value+1 | adc value+1 | ||
sta value+1 | sta value+1 | ||
</ | </ | ||
+ | |||
---- | ---- | ||
- | White Flame (aka David Holz) | + | White Flame |
base/signed_8bit_16bit_addition.txt · Last modified: 2018-09-28 05:20 by white_flame